bigpotato
bigpotato

Reputation: 27547

Rails 4: Can I open up a model a second time to define a method?

I'm using the globalize gem to translate the name attribute of my Color model. The gem seems to generate a Color::Translation ActiveRecord model, but it doesn't provide the file in app/models.

I want to add validations to this model, so I'm wondering if I can just create a file called app/models/color_translations.rb and do something like:

class Color::Translation < ActiveRecord::Base
  validates_presence_of :name
end

would this extend the class's functionality (which is what I want) or overwrite everything (unwanted)?

Upvotes: 1

Views: 25

Answers (1)

Frederick Cheung
Frederick Cheung

Reputation: 84172

This depends slightly on context. If there is a class Color::Translation then the result of loading your app/models/color_translations.rb file will be to add that validation. However if there is no such class, then it will define a new one.

The tricky thing in development is that classes are (in general) loaded on demand - you don't in general know what is already loaded versus what could be loaded. One way around this is to do

Color::Translation.class_eval do
  validates_presence_of :name
end

which will never create a new class - it will use an existing one (if necessary Rails' autoloading will kick in) but if it can't find one it will raise an error.

The second problem you'll have is also related: if you stick this in a file in app/models how will rails know to load it if the class already exists?

It looks like globalizes creates these classes on the fly, so the safest place is to put this at the bottom of color.rb. This also ensures that if rails reloads Color and globalize thus creates a new Color::Translation that you validation will get added to this new class too.

Upvotes: 1

Related Questions