Rails console includes differently than model -
tl;dr: include mymodule
brings mymodule
's functions scope when run in rails console, not when in rails model. don't understand , able access these functions in model.
i have file lib/zip_validator.rb
, use validate user input user
model.
module activemodel::validations::helpermethods def validates_zip(*attr_names) validates_with zipvalidator, _merge_attributes( attr_names ) end end class zipvalidator < activemodel::eachvalidator def validate_each( record, attr_name, value ) unless is_legitimate_zipcode( self.zip ) record.errors.add( attr_name, :zip, options.merge( value: value )) end end end
in rails console, can do
irb(main):005:0> include activemodel::validations::helpermethods => object irb(main):006:0> validates_zip nomethoderror: undefined method `validates_with' main:object /home/bistenes/programming/myapp/lib/zip_validator.rb:3:in `validates_zip' (irb):6 /usr/lib64/ruby/gems/1.9.1/gems/railties-3.2.13/lib/rails/commands/console.rb:47:in `start' /usr/lib64/ruby/gems/1.9.1/gems/railties-3.2.13/lib/rails/commands/console.rb:8:in `start' /usr/lib64/ruby/gems/1.9.1/gems/railties-3.2.13/lib/rails/commands.rb:41:in `<top (required)>' script/rails:6:in `require' script/rails:6:in `<main>'
look! found validates_zip
, because it's complaining call within method. maybe complaint go away when try , call model it's going used, app/models/user.rb
:
class user < activerecord::base include activemodel::validations::helpermethods attr_accessible :first_name, :last_name, :zip, :email, :password, :password_confirmation, :remember_me, :confirmed_at validates_presence_of :first_name, :last_name, :zip validates_zip :zip
when attempt start server (thin), errors out with:
/usr/lib64/ruby/gems/1.9.1/gems/activerecord-3.2.13/lib/active_record/dynamic_matchers.rb:55:in `method_missing': undefined method `validates_zip' #<class:0x00000003e03f28> (nomethoderror) /home/bistenes/programming/myapp/app/models/user.rb:38:in `<class:user>'
what in world going on? why server fail find function console found?
consider this:
module m def m end end class c include m end
given that, can c.new.m
without complaint can't c.m
. what's going on here? when include m
, methods in m
added c
instance methods if wanted say:
class c include m m end
then m
have class method since self
when call m
here class itself. can using included
hook in module:
module m def self.included(base) base.class_exec def m end end end end class c include m m # works end
in case, you'd have this:
module activemodel::validations::helpermethods def self.included(base) base.class_exec def self.validates_zip(*attr_names) validates_with zipvalidator, _merge_attributes( attr_names ) end end end end
now user
have validates_zip
class method can call in desired context.
Comments
Post a Comment