Module: Stipulate::ClassMethods

Defined in:
lib/stipulate.rb

Instance Method Summary collapse

Instance Method Details

#stipulate(opts = {}) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/stipulate.rb', line 9

def stipulate(opts={})
  method = opts[:that].to_s
  enumeration = method.pluralize

  singleton_class.class_eval "    cattr_accessor :\#{enumeration}\n  END\n  \n  # If the method is customized, we want to retain changes through a wrapper\n  if instance_methods.include? method.to_sym\n    class_eval <<-\"END\"\n      # Ensure fields are converted to string\n      def \#{method}_with_stipulation\n        v = \#{method}_without_stipulation\n        v.nil? ? nil : v.to_s\n      end\n    END\n  \n    alias_method_chain method.to_sym, :stipulation\n  else\n    class_eval <<-\"END\"\n      # Ensure fields are converted to string\n      def \#{method}\n        v = attributes[\"\#{method}\"]\n        v.nil? ? nil : v.to_s\n      end\n    END\n  end\n  \n  singleton_class.send :\"\#{enumeration}=\", opts[:can_be]\n  \n  for enum in opts[:can_be] do\n    class_eval <<-\"END\"\n      def \#{enum}?\n        \#{method}.to_s.to_sym == :\#{enum}\n      end\n    END\n  end\nend\n"