lib/frenchy/model.rb in frenchy-0.4.0 vs lib/frenchy/model.rb in frenchy-0.5.0

- old
+ new

@@ -75,10 +75,19 @@ end const_set(name.to_s.camelize, klass) klass.class_eval(&block) end + # Macro to add an enum type + def enum(name, &block) + klass = Class.new(self) do + include Frenchy::Enum + end + const_set(name.to_s.camelize, klass) + klass.class_eval(&block) + end + # Macro to create a subtype and associated field def embed(name, options={}, &block) type(name, &block) field(name, options.merge({type: name})) end @@ -86,10 +95,15 @@ # Macro to add a field def field(name, options={}) name = name.to_s options.stringify_keys! + if options["enum"] + options["type"] = "enum" + options["class_name"] ||= options["enum"].to_s.camelize + end + type = (options["type"] || "string").to_s aliases = (options["aliases"] || []) aliases.each do |a| define_method("#{a}") do @@ -156,9 +170,18 @@ options["default"] ||= {} # Convert value to a Hash define_method("#{name}=") do |v| set(name, Hash[v]) + end + + when "enum" + # Resolve the class name + klass = const_get(options["class_name"]) + + # Convert value to enum class + define_method("#{name}=") do |v| + set(name, klass.find(v.to_i)) end else # Unknown types have their type constantized and initialized with the value. This # allows us to support things like other Frenchy::Model classes, ActiveRecord models, etc.