Posts Tagged activerecord

Ruby on Rails dynamic finder – find_or_create method

Here is another one I was not aware of. I knew you could use dynamic finders to look for one or more attributes, but I did not realize you could do a find and create at the same time (well.. not really both of them at once, but you know what I mean)

Blog.find_or_create_by_title("Some Blog")

If there is a blog with title = “Some Blog”, then it will pull this blog out of the table. If the blog does not exist, a new Blog is created with the title “Some Blog”. Alternately you can use find_or_initialize_by_name and it will not save the object to the database immediately.. it will be available in the scope of your code, just as if you called blog = Blog.new(:title=>”Some Blog”)

This could come in handy in certain situations and save you a line of code. Daddy like

Tags: ,

Ruby programming – what is dollar sign colon .unshift ($:.unshift) ??

This is a special variable in ruby. Ruby special variables start with the dollar sign followed by a single character. This particular variable is the default search path for load or require. If you call it in irb or the rails console, you can see it returns an array of strings which are paths.

Since it returns an array, the unshift is simply an array method that adds an object to the beginning of an array.

An example of this can be seen in the ActiveRecord source (2.3.2 rails). In this particular example, the ActiveSupport path is prepended to the array, so that it can be required in the code.

activesupport_path = "#{File.dirname(__FILE__)}/../../activesupport/lib"
if File.directory?(activesupport_path)
  $:.unshift activesupport_path
  require 'active_support'
end

There are a bunch of other special variables in ruby like this one. Take a look here for more info: http://www.zenspider.com/Languages/Ruby/QuickRef.html#18

Tags: , ,