How to perform Rails model validation checks within model but outside of filters using ledermann-rails-settings and extensions

Posted by user1277160 on Stack Overflow See other posts from Stack Overflow or by user1277160
Published on 2012-03-18T17:59:13Z Indexed on 2012/03/18 18:02 UTC
Read the original article Hit count: 230

Background

I'm using ledermann-rails-settings (https://github.com/ledermann/rails-settings) on a Rails 2/3 project to extend virtually the model with certain attributes that don't necessarily need to be placed into the DB in a wide table and it's working out swimmingly for our needs.

An additional reason I chose this Gem is because of the post How to create a form for the rails-settings plugin which ties ledermann-rails-settings more closely to the model for the purpose of clean form_for usage for administrator GUI support. It's a perfect solution for addressing form_for support although...

Something that I'm running into now though is properly validating the dynamic getters/setters before being passed to the ledermann-rails-settings module. At the moment they are saved immediately, regardless if the model validation has actually fired - I can see through script/console that validation errors are being raised.

Example

For instance I would like to validate that the attribute :foo is within the range of 0..100 for decimal usage (or even a regex). I've found that with the previous post that I can use standard Rails validators (surprise, surprise) but I want to halt on actually saving any values until those are addressed - ensure that the user of the GUI has given 61.43 as a numerical value.

The following code has been borrowed from the quoted post.

class User < ActiveRecord::Base

  has_settings

  validates_inclusion_of :foo, :in => 0..100

  def self.settings_attr_accessor(*args)

    >>SOME SORT OF UNLESS MODEL.VALID? CHECK HERE      

      args.each do |method_name|
        eval "
          def #{method_name}
            self.settings.send(:#{method_name})
          end
          def #{method_name}=(value)
            self.settings.send(:#{method_name}=, value)
          end
        "
      end

    >>END UNLESS

  end

  settings_attr_accessor :foo

end


Anyone have any thoughts here on pulling the state of the model at this point outside of having to put this into a before filter? The goal here is to be able to use the standard validations and avoid rolling custom validation checks for each new settings_attr_accessor that is added. Thanks!

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about validation