module Gifnoc::TypedAttrAccessor
Constants
- TYPE_BASE64
- TYPE_BOOLEAN
- TYPE_DATE_TIME
- TYPE_HASH
- TYPE_INTEGER
- TYPE_STRING
Public Class Methods
allowed_types(type_alias)
click to toggle source
# File lib/gifnoc/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)
click to toggle source
# File lib/gifnoc/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)
click to toggle source
# File lib/gifnoc/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)
click to toggle source
# File lib/gifnoc/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
Public Instance Methods
typed_attr_accessor(name, type_alias)
click to toggle source
# File lib/gifnoc/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