Is there any built-in way to automatically enforce a type/class on an instance variable in Ruby? -


i'm working ruby , rails, rails extension of ruby should fine too.

i'm wondering if there's way force type on instance variables (rather, setters , getters) that's easier manually defining them.

the class method attr_accessor , don't enforce type. noticed instance rails' activerecord::base class automatic casting on setters. knows database particular active record variable integer, , setting @record.integer_variable = '1' automatically casts argument , allows further access through @record.integer_variable # => 1.

is there way tap this?

i write own getters , setters class methods, if smarter folk have done heavy lifting, i'd rather not have trust myself.

i don't know if there's it, can solve problem few lines of meta-programming:

module enforcetypes   def attr_accessor_of_type(name, type)     send :define_method, name       instance_variable_get("@#{name}")     end     send :define_method, "#{name}=" |v|       raise argumentexception unless v.is_a? type       instance_variable_set("@#{name}", v)     end   end end 

usage:

class myclass   extend enforcetypes    attr_accessor_of_type :some_string, string end 

of course can make little smart changing 2nd emitted method, performing conversions, etc.

here's nice reference: http://www.raulparolari.com/ruby2/attr_accessor

and remember, can manually copy-and-pasting lots of code, can solved meta-programming.


Comments

Popular posts from this blog

c++ - Is it possible to compile a VST on linux? -

java - Output of Eclipse is rubbish -

jquery - Confused with JSON data and normal data in Django ajax request -