whatsapp_btn
whatsapp_btn Chat With Us

Home >> RoR >> Explaining Some Magic Codes of Ruby on Rails

Explaining Some Magic Codes of Ruby on Rails

  6 min read
Explaining Some Magic Codes of Ruby on Rails

Ruby on Rails is the best platform for writing code for websites. It is a well-known web framework that will make the coding process quick and accurate. You can describe Rails magic as all the functionalities that the Ruby on Rails web application framework provides. These ROR magic codes help to determine the best functionalities of this framework. Ruby on Rails is popular among developers because it follows TDD (Test Driven Approach) and has better testing capabilities than other frameworks.

That’s why Ruby on Rails websites are stable and maintainable. This framework also includes several automatic tests which make the websites more reliable. It is a framework that helps developers to build various applications and websites by simplifying repetitive tasks. Ruby on Rails framework provides a better structure to write the code.

Tricky methods to convert strings, arrays, and hashes

Arrays, Strings, and Hashes are data structures that allow developers to store multiple values at once. An array is a collection of similar or different items stored at nearby locations. Hash is a collection of unique keys and their values. Here you will see some tricky methods to convert strings, arrays, and hashes.

[4] pry(main)> "ClassName".parameterize
=> "classname"

[6] pry(main)> "className".capitalize
=> "Classname"

[14] pry(main)> "User".constantize
=> User (call 'User.connection' to establish a connection)

[26] pry(main)> "Class Name".parameterize(separator: "_")
=> "class_name"

[36] pry(main)> "Class Name".parameterize.underscore
=> "class_name"

[76] pry(main)> "class-name".underscore.camelize(:lower)
=> "className"

irb(main):015:0> 'class_name'.humanize
=> "Class name"

Underscore + camelize

There is an inbuilt method called underscore that you can use to convert camel case to underscore in Ruby. This underscore method is widely known as the inverse of camelize. Here you will see the examples of using the underscore and camelize method when you are coding.

[69] pry(main)> "aaa-aaa".underscore.camelize(:lower)
=> "aaaAaa"

Numbers to ordinalize

The Ruby on Rails framework is full of interesting features. You will see that ordinalize is a number extension that will return the corresponding ordinal number as a string. Here you will get the example of numbers to ordinalize.

irb(main):018:0> 3.ordinalize
=> "3rd"
irb(main):019:0> 21.ordinalize
=> "21st"

Array to string

In Ruby, if you want to convert an array into a string then you have to use the join method. This join method will take the array and separator as the arguments. After that, it will separate all the elements of the array with the help of a specific value of the separator.

[46] pry(main)> ["a", "b"].join
=> "ab"

[47] pry(main)> ["a", "b"].join(" ")
=> "a b"

[48] pry(main)> ["a", "b"].join(", ")
=> "a, b"

> ["", "22", "14", "18"].map(&:to_i) 
# Result: [0, 22, 14, 18]

Array  intersection, union & subtraction

If you want to do the procedure of array intersection, union, and subtraction then you can do it with the help of the intersection, union, and different methods. Here you can see the example of array union, intersection, and subtraction.

x = [1, 1, 2, 4] 
y = [1, 2, 2, 2] 

# intersection 
x & y # => [1, 2] 

# union x | y 
# => [1, 2, 4] 

# difference x - y 
# => [4]

Do you want to take your Ruby on Rails skills to the next level?

Discover the magic codes behind Ruby on Rails and unlock its full potential. Our in-depth explanation of these codes will answer all your burning questions and help you become a more proficient developer. Contact us today to learn more and take the first step towards mastering Ruby on Rails.


Getting values of Hash

The map is a method in ruby that you can use in Hash. The main use of a map is to transform the data. If you are trying to get values of Hash then you can use the map method and get values stored in a hash. Here is an example of a map that you can use to get values of hash.

h = { a: 1, b: 2, c: 3, d: 4 }
[ :a, :c, :d, :b ].map(&h)
# => [ 1, 3, 4, 2 ]

Hash neat trick

redirect_conditions = {
      no_first_confition: first_confition.nil?,
      no_second_condition: second_condition?,
      no_third_condition: third_condition.blank?,
      no_fourth_condition: fourth_condition.none?,
    }

    if redirect_conditions.value?(true)

# equivalent: 
If first_confition.nil? &&                                                                                                   second_condition? && 
third_condition.blank? && 
fourth_condition.none?

Ruby grep method:

Grep is a method that can be used to filter the entire countable object like ranges and arrays. You will see that Grep works in a different way than the Select method and gives different results. Here you can see how you can use the grep method in Ruby.

Read More: What is Ruby on Rails & Why is it Used for Web Applications?

<!-- wp:code {"backgroundColor":"black","textColor":"white"} -->
<pre class="wp-block-code has-white-color has-black-background-color has-text-color has-background"><code>irb(main):066:0&gt; objects = &#91;"a", "b", "c",1, 2,nil]
=&gt; &#91;"a", "b", "c", 1, 2, nil]
irb(main):067:0&gt; objects.grep(String)
=&gt; &#91;"a", "b", "c"]
irb(main):068:0&gt; objects.grep(Integer)
=&gt; &#91;1, 2]

irb(main):073:0&gt; fruits = &#91;"apple", "banana", "orange"]
=&gt; &#91;"apple", "banana", "orange"]
irb(main):074:0&gt; fruits.grep(/^a/)
=&gt; &#91;"apple"]
irb(main):075:0&gt; fruits.grep(/e$/)
=&gt; &#91;"apple", "orange"]
irb(main):076:0&gt; numbers = &#91;14, 1, 2, 3,6]
=&gt; &#91;14, 1, 2, 3, 6]
irb(main):077:0&gt; numbers.grep(&#91;1..6])
=&gt; &#91;]
irb(main):078:0&gt; numbers.grep(1..6)
=&gt; &#91;1, 2, 3, 6]
irb(main):079:0&gt; </code></pre>
<!-- /wp:code -->

Active storage attachment with join table

class User < ActiveRecord::Base
 	has_one_attached :image
end

You can do that using left_joins with the name of the association (image + _attachment) which is interpreted as:

SELECT users.* FROM users LEFT OUTER JOIN active_storage_attachments ON active_storage_attachments.record_id = users.id AND active_storage_attachments.record_type = 'User' AND active_storage_attachments.name = 'image'

And then apply a WHERE filter to get those user rows without matching against the active_storage_attachments table:

User.left_joins(:image_attachment).where(active_storage_attachments: { id: nil })

Extract associations form a collection

post.comments.extract_associated(:user)
	
# equivalent:
post.comments.preload(:user).collect(&:user)

Are you curious about the inner workings of Ruby on Rails?

Get an inside look at the magic codes that power Ruby on Rails. Hire our Developers to learn more about our in-depth explanation of these codes.


Conclusion

You can hire a Ruby on Rails developer if you are trying to have a web application. I hope that you find these snippets of coding in Ruby helpful. These coding snippets will show the importance of Ruby on Rails and how it helps developers to build websites and applications.

If you like these magic codes of Ruby on Rails then you should hire a Ruby on Rails Development Company that uses these magic codes to build a fully functional application for the growth of your business.

Soham
Tagline Infotech is a Software engineer at Tagline infotech. He has more than 2 years of experience in Ruby on Rails development, and also has expertise in CRM, Integration management, data processing, and APIs.

Related Posts :

contact-us-bg

Our Global Presence

India

Surat (HQ)

Digital Valley, 423, Apple Square, beside Lajamni Chowk, Mota Varachha, Surat, Gujarat 394101

Ahmedabad

D-401, titanium city center, 100 feet anand nagar road, Ahmedabad-380015

 +91 9913 808 285

U.S.A

1133 Sampley Ln Leander, Texas, 78641

United Kingdom

52 Godalming Avenue, wallington, London - SM6 8NW

U.A.E

Office No - 43-44, Al Fahidi, Bur Dubai, Dubai, United Arab Emirates

 +971 58 569 4786