Class: ClientDataAdapter::Wrapper

Inherits:
Object
  • Object
show all
Defined in:
lib/client-data-adapter/wrapper.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(target, &block) ⇒ Wrapper

Returns a new instance of Wrapper.



12
13
14
15
16
# File 'lib/client-data-adapter/wrapper.rb', line 12

def initialize(target, &block)
  @target = target

  self.class.module_eval(&block)
end

Instance Attribute Details

#targetObject (readonly)

Instance of original class.

Examples:

@book.adapter_wrapper.target == @book # => true


10
11
12
# File 'lib/client-data-adapter/wrapper.rb', line 10

def target
  @target
end

Class Method Details

.adapter(&block) ⇒ Hash

Main adapter method, should return Hash.

Syntactic sugar of with.

Examples:

define_adapter do

  adapter do
    {
      id: id,
      title: title,
    }
  end

end

Returns:

  • (Hash)

See Also:



36
37
38
# File 'lib/client-data-adapter/wrapper.rb', line 36

def self.adapter(&block)
  with('__adapter__', &block)
end

Used in one-to-many relationship.

Syntactic sugar of with.

Examples:

define_adapter do

  link_many(:link1, :link2)
  # ...

end

Parameters:

  • associations (Symbol)

See Also:



78
79
80
81
82
83
84
85
86
# File 'lib/client-data-adapter/wrapper.rb', line 78

def self.link_many(*associations)
  associations.each do |assoc|
    with(assoc) do |*args|
      (public_send(assoc.to_sym) || []).map do |elem|
        elem.adapter(*args)
      end
    end
  end
end

Used in one-to-one relationship.

Syntactic sugar of with.

Examples:

define_adapter do

  link_one(:link1, :link2)
  # ...

end

Parameters:

  • associations (Symbol)

See Also:



53
54
55
56
57
58
59
60
61
62
63
# File 'lib/client-data-adapter/wrapper.rb', line 53

def self.link_one(*associations)
  associations.each do |assoc|
    with(assoc) do |*args|
      obj = public_send(assoc.to_sym)

      if obj.respond_to?(:adapter)
        obj.adapter(*args)
      end
    end
  end
end

.with(method_name, &block) ⇒ Object

Define a method of Wrapper.

Merged to the result of adapter method.

Examples:

define_adapter do
  # ...

  with :something do
    # do something
  end

end

Parameters:

  • method_name (Symbol)


102
103
104
105
106
107
108
109
# File 'lib/client-data-adapter/wrapper.rb', line 102

def self.with(method_name, &block)
  define_method(method_name.to_sym) do |*args|
    target.instance_exec(
      *args,
      &Util.to_lambda(block)
    )
  end
end