Module: ConfigStore::TypedAttrAccessor
- Included in:
- Model
- Defined in:
- lib/configstore/models/typed_attr_accessor.rb
Constant Summary collapse
- TYPE_STRING =
:string
- TYPE_DATE_TIME =
:date_time
- TYPE_BOOLEAN =
:boolean
- TYPE_INTEGER =
:integer
- TYPE_HASH =
:hash
- TYPE_BASE64 =
:base64
Class Method Summary collapse
- .allowed_types(type_alias) ⇒ Object
- .type_alias_to_type_array(type_alias) ⇒ Object
- .type_checks(type_alias, value) ⇒ Object
- .type_specific_checks(type_alias, value) ⇒ Object
Instance Method Summary collapse
Class Method Details
.allowed_types(type_alias) ⇒ Object
25 26 27 28 29 30 |
# File 'lib/configstore/models/typed_attr_accessor.rb', line 25 def self.allowed_types(type_alias) allowed_types = [] allowed_types += [NilClass] allowed_types += type_alias_to_type_array(type_alias) return allowed_types end |
.type_alias_to_type_array(type_alias) ⇒ Object
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/configstore/models/typed_attr_accessor.rb', line 32 def self.type_alias_to_type_array(type_alias) case type_alias when TYPE_STRING return [String] when TYPE_BASE64 return [String] when TYPE_DATE_TIME return [DateTime] when TYPE_BOOLEAN return [TrueClass, FalseClass] when TYPE_INTEGER return [Integer] when TYPE_HASH return [Hash] end end |
.type_checks(type_alias, value) ⇒ Object
49 50 51 52 |
# File 'lib/configstore/models/typed_attr_accessor.rb', line 49 def self.type_checks(type_alias, value) allowed_types = self.allowed_types(type_alias) raise ArgumentError.new("Invalid Type (allowed #{ allowed_types.inspect })") unless allowed_types.any? { |type| value.is_a?(type) } end |
.type_specific_checks(type_alias, value) ⇒ Object
54 55 56 57 58 59 |
# File 'lib/configstore/models/typed_attr_accessor.rb', line 54 def self.type_specific_checks(type_alias, value) case type_alias when TYPE_BASE64 Base64.strict_decode64(value) if value # raises ArgumentError (invalid base64) if value is not a Base64 string end end |
Instance Method Details
#typed_attr_accessor(name, type_alias) ⇒ Object
13 14 15 16 17 18 19 20 21 22 23 |
# File 'lib/configstore/models/typed_attr_accessor.rb', line 13 def typed_attr_accessor(name, type_alias) define_method(name) do instance_variable_get("@#{name}") end define_method("#{name}=") do |value| TypedAttrAccessor.type_checks(type_alias, value) TypedAttrAccessor.type_specific_checks(type_alias, value) instance_variable_set("@#{name}", value) end end |