Module: Degu::HasSet

Extended by:
ActiveSupport::Concern
Included in:
ActiveRecord::Base
Defined in:
lib/degu/has_set.rb

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#has_set_coerce_argument_value(enum_class, argument_value) ⇒ Object

Understands the arguments as the list of enum values

The argument value can be
  - a `string` of enum values joined by a comma
  - an enum constant
  - a `symbol` which resolves to the enum constant
  - an `integer` as the index of the enum class
If you have just 1 value, you do not need to enclose it in an `Array`


111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/degu/has_set.rb', line 111

def has_set_coerce_argument_value(enum_class, argument_value)
  invalid_set_elements = []
  set_elements =
    if String === argument_value
      argument_value.split(',').map(&:strip)
    else
      Array(argument_value)
    end.map do |set_element|
      if result = enum_class[set_element]
        result
      else
        invalid_set_elements << set_element
        nil
      end
    end
  invalid_set_elements.empty? or
    raise ArgumentError, "element #{argument_value.inspect} contains invalid elements: #{invalid_set_elements.inspect}"
  set_elements
end

#read_set_attribute(attribute_name) ⇒ Object

Just a small wrapper about the ‘ActiveRecord::Base#read_attribute` method, which also checks the type

of the column and converts the value to an `Integer` if `String` is given.


86
87
88
89
90
91
# File 'lib/degu/has_set.rb', line 86

def read_set_attribute(attribute_name)
  value = read_attribute(attribute_name)
  column_type = ((column_definition = self.class.columns_hash[attribute_name.to_s]) and column_definition.type)
  value = value.to_i(10) if column_type == :string
  value
end

#write_set_attribute(attribute_name, value) ⇒ Object

Just a small wrapper about the ‘ActiveRecord::Base#write_attribute` method, which also checks the type

of the column and converts the value to an `String` if `String` is the column type. This is needed because
implicit conversion produces something like `3.4532454354325645e+17` instead of an `integer`


97
98
99
100
101
# File 'lib/degu/has_set.rb', line 97

def write_set_attribute(attribute_name, value)
  column_type = ((column_definition = self.class.columns_hash[attribute_name.to_s]) and column_definition.type)
  value = value.to_s(10) if column_type == :string
  write_attribute(attribute_name, value)
end