lib/torque/postgresql/attributes/builder/enum.rb in torque-postgresql-0.2.14 vs lib/torque/postgresql/attributes/builder/enum.rb in torque-postgresql-0.2.15

- old
+ new

@@ -2,11 +2,11 @@ module PostgreSQL module Attributes module Builder class Enum - attr_accessor :klass, :attribute, :subtype, :options, :values + attr_accessor :klass, :attribute, :subtype, :options, :values, :enum_module # Start a new builder of methods for composite values on # ActiveRecord::Base def initialize(klass, attribute, subtype, options) @klass = klass @@ -72,13 +72,18 @@ MSG end # Create all methods needed def build + @enum_module = Module.new + plural text all_values + + klass.include enum_module + klass.extend enum_module::ClassMethods end private # Check if the method already exists in the reference class @@ -96,11 +101,12 @@ # Create the method that allow access to the list of values def plural attr = attribute enum_klass = subtype.klass - klass.singleton_class.module_eval do + enum_module.const_set('ClassMethods', Module.new) + enum_module::ClassMethods.module_eval do # def self.statuses() statuses end define_method(attr.pluralize) do enum_klass.values end @@ -111,33 +117,34 @@ end end # def self.statuses_options() statuses_texts.zip(statuses) end define_method(attr.pluralize + '_options') do - enum_klass.values + public_send(attr.pluralize + '_texts').zip(enum_klass.values) end end end # Create the method that turn the attribute value into text using # the model scope def text attr = attribute - klass.module_eval do + enum_module.module_eval do # def status_text() status.text('status', self) end define_method("#{attr}_text") { send(attr).text(attr, self) } end end # Create all the methods that represent actions related to the # attribute value def all_values attr = attribute vals = values_methods - klass.module_eval do + model_klass = klass + enum_module.module_eval do vals.each do |val, list| # scope :disabled, -> { where(status: 'disabled') } - scope list[0], -> { where(attr => val) } + model_klass.scope list[0], -> { where(attr => val) } # def disabled? status.disabled? end define_method(list[1]) { send(attr).public_send("#{val}?") } # def disabled! enum_save_on_bang ? update!(status: 'disabled') : status.disabled! end