Skip to content
Andrew Geweke edited this page Dec 13, 2013 · 1 revision

When you define a flex column, methods are automatically generated for each attribute. By default, these are public, although you can make them private. By default, methods are generated on the outer model class that delegate to the methods on the flex column, although you can change this, too.

These methods are actually present on a generated module that gets included into the flex-column class itself, rather than created on the flex-column class directly. As a result, you can override these methods yourself, and everything will work just fine:

class User < ActiveRecord::Base
  flex_column :user_attributes do
    field :total_emails_delivered
    field :background_color

    def background_color
      super.try(:to_sym)
    end

    def total_emails_delivered=(x)
      super([ x, 100 ].min)
    end
  end
end

my_user = User.find(...)
my_user.user_attributes.total_emails_delivered = 173
my_user.total_emails_delivered # => 100
my_user.background_color       # => :green, or whatever

Because methods on the model class delegate to these methods automatically, you don't need to override them there, too:

my_user = User.find(...)
my_user.total_emails_delivered = 209
my_user.total_emails_delivered # => 100
my_user.background_color       # => :green, or whatever

The delegate methods created on the outer model class are also actually defined on a generated module that gets included into that class; as a result, you can override them there, and super will work correctly, too.

If you override methods on the model class, however, be aware that this (of course) does not override methods on the flex-column object — for example:

class User < ActiveRecord::Base
  flex_column :user_attributes do
    field :total_emails_delivered
    field :background_color
  end

  def background_color
    super.try(:to_sym)
  end

  def total_emails_delivered=(x)
    super([ x, 100 ].min)
  end
end

my_user = User.find(...)
my_user.total_emails_delivered = 209
my_user.total_emails_delivered # => 100

but:

my_user.user_attributes.total_emails_delivered = 209
my_user.total_emails_delivered # => 209
Clone this wiki locally