Class: Evil::Client::Model

Inherits:
Object
  • Object
show all
Extended by:
Dry::Initializer
Defined in:
lib/evil/client/model.rb

Overview

Data structure with validators and memoizers

Direct Known Subclasses

Settings

Class Method Summary collapse

Class Method Details

.extend(other) ⇒ self

Merges [.option]-s, virtual attributes [.let] and [.validation]-s from another model into the current one.



82
83
84
85
86
87
# File 'lib/evil/client/model.rb', line 82

def extend(other)
  return super if other.instance_of? Module

  validate_model other
  extend_model   other
end

.let(key, &block) ⇒ self

Creates or reloads memoized attribute



38
39
40
41
42
43
44
45
46
47
48
# File 'lib/evil/client/model.rb', line 38

def let(key, &block)
  NameError.check!(key)
  lets[key.to_sym] = block

  define_method(key) do
    instance_variable_get(:"@#{key}") ||
      instance_variable_set(:"@#{key}", instance_exec(&block))
  end

  self
end

.letsHash<Symbol, Proc>

Definitions for virtual attributes



54
55
56
# File 'lib/evil/client/model.rb', line 54

def lets
  @lets ||= {}
end

.new(options = {}, **kwargs) ⇒ Evil::Client::Model Also known as: call

Model instance constructor



94
95
96
97
# File 'lib/evil/client/model.rb', line 94

def new(options = {}, **kwargs)
  kwargs = Hash(options).transform_keys(&:to_sym).merge(kwargs)
  super(**kwargs).tap { |item| in_english { policy[item].validate! } }
end

.option(key, type = nil, as: key.to_sym, **opts) ⇒ self

Creates or updates the settings’ initializer

Options Hash (**opts):

  • :type (#call)

    Another way to assign type coercer

  • :default (#call)

    Proc containing default value

  • :optional (Boolean)

    Whether it can be missed

  • :as (#to_sym)

    The name of settings variable

  • :reader (false, :private, :protected)

    Reader method type

See Also:



25
26
27
28
29
# File 'lib/evil/client/model.rb', line 25

def option(key, type = nil, as: key.to_sym, **opts)
  NameError.check!(as)
  super
  self
end

.options(key, type = nil, opts = {}) ⇒ self

Creates or updates the settings’ initializer

Options Hash (opts):

  • :type (#call)

    Another way to assign type coercer

  • :default (#call)

    Proc containing default value

  • :optional (Boolean)

    Whether it can be missed

  • :as (#to_sym)

    The name of settings variable

  • :reader (false, :private, :protected)

    Reader method type

See Also:



25
26
27
28
29
# File 'lib/evil/client/model.rb', line 25

def option(key, type = nil, as: key.to_sym, **opts)
  NameError.check!(as)
  super
  self
end

.policyEvil::Client::Policy

Policy object for model instances



62
63
64
# File 'lib/evil/client/model.rb', line 62

def policy
  @policy ||= superclass.policy.for(self)
end

.validate(&block) ⇒ self

Add validation rule to the [#policy]



71
72
73
74
# File 'lib/evil/client/model.rb', line 71

def validate(&block)
  policy.validate(&block)
  self
end