Module: Chozo::VariaModel::ClassMethods

Defined in:
lib/chozo/varia_model.rb

Constant Summary collapse

ASSIGNMENT_MODES =
[
  :whitelist,
  :carefree
]

Instance Method Summary collapse

Instance Method Details

#assignment_modeSymbol

Returns:

  • (Symbol)


25
26
27
# File 'lib/chozo/varia_model.rb', line 25

def assignment_mode
  @assignment_mode ||= :whitelist
end

#attribute(name, options = {}) ⇒ Object

Parameters:

  • name (#to_s)
  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :type (Symbol, Array<Symbol>)
  • :required (Boolean)
  • :default (Object)
  • :coerce (Proc)


49
50
51
52
53
54
55
56
# File 'lib/chozo/varia_model.rb', line 49

def attribute(name, options = {})
  name = name.to_s
  options[:type] = Array(options[:type])
  options[:required] ||= false

  register_attribute(name, options)
  define_mimic_methods(name, options)
end

#attributesHashie::Mash

Returns:



15
16
17
# File 'lib/chozo/varia_model.rb', line 15

def attributes
  @attributes ||= Hashie::Mash.new
end

#set_assignment_mode(mode) ⇒ Object

Set the attribute mass assignment mode

* :whitelist - only attributes defined on the class will have values set
* :carefree  - values will be set for attributes that are not explicitly defined
               in the class definition

Parameters:



36
37
38
39
40
41
42
# File 'lib/chozo/varia_model.rb', line 36

def set_assignment_mode(mode)
  unless ASSIGNMENT_MODES.include?(mode)
    raise ArgumentError, "unknown assignment mode: #{mode}"
  end

  @assignment_mode = mode
end

#validate_kind_of(types, model, key) ⇒ Array

Parameters:

  • types (Constant, Array<Constant>)
  • model (VariaModel)
  • key (String)

Returns:

  • (Array)


70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/chozo/varia_model.rb', line 70

def validate_kind_of(types, model, key)
  errors  = Array.new
  types   = types.uniq
  matches = false

  types.each do |type|
    if model.get_attribute(key).is_a?(type)
      matches = true
      break
    end
  end

  if matches
    [ :ok, "" ]
  else
    types_msg = types.collect { |type| "'#{type}'" }
    [ :error, "Expected attribute: '#{key}' to be a type of: #{types_msg.join(', ')}" ]
  end
end

#validate_required(model, key) ⇒ Array

Validate that the attribute on the given model has a non-nil value assigned

Parameters:

Returns:

  • (Array)


96
97
98
99
100
101
102
# File 'lib/chozo/varia_model.rb', line 96

def validate_required(model, key)
  if model.get_attribute(key).nil?
    [ :error, "A value is required for attribute: '#{key}'" ]
  else
    [ :ok, "" ]
  end
end

#validationsHashie::Mash

Returns:



20
21
22
# File 'lib/chozo/varia_model.rb', line 20

def validations
  @validations ||= Hashie::Mash.new
end

#validations_for(name) ⇒ Array

Parameters:

  • name (String)

Returns:

  • (Array)


61
62
63
# File 'lib/chozo/varia_model.rb', line 61

def validations_for(name)
  self.validations[name] ||= Array.new
end