I was learning some Rspec stuff and accidentally introduced some code into my model class which I expected to create an error. But to my surprise there were non.
class Address < ActiveRecord::Base
attr_accessible :city, :country, :person_id, :street, :zip
validates_presence_of :city, :zip, :street
before_save :setDefaultCountry
# -- Beginning strange code --
if true
puts "Hey! I shouldn't be able to do this"
end
# -- End of strange code --
private
def setDefaultCountry
if self.country.blank?
self.country = "US"
end
end
end
This is the rails console output:
Arman$ rails console
Loading development environment (Rails 3.2.3)
1.9.3p194 :001 > a = Address.new
Hey! I shouldn't be able to do this
=> #<Address id: nil, street: nil, city: nil, zip: nil, country: nil, person_id: nil, created_at: nil, updated_at: nil>
1.9.3p194 :002 >
Why isn’t ruby complaining about strange code being added inside the class definition?
That’s just how ruby works. You don’t think that
attr_accessibleshould cause error, do you? But this is just a regular method call! Here’s its sourceYou can run arbitrary ruby code in the class definition. This is a feature, not a bug 🙂