Module: Models::LiquidMethods::ClassMethods

Defined in:
app/concerns/models/liquid_methods.rb

Overview

Class-level DSL declared by including models.

Instance Method Summary collapse

Instance Method Details

#liquid_methods(*allowed_methods) ⇒ void

This method returns an undefined value.

Builds a Liquid drop exposing the given methods and defines to_liquid
on the model to return it. ActiveRecord relations are materialized to
arrays because Liquid can't iterate other collection types.

Parameters:

  • allowed_methods (Array<Symbol>)

    model methods exposed to Liquid



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'app/concerns/models/liquid_methods.rb', line 19

def liquid_methods(*allowed_methods)
  drop_class = const_set(:LiquidDropClass, Class.new(Liquid::Drop))

  define_method :to_liquid do
    drop_class.new(self)
  end

  drop_class.class_eval do
    def initialize(object)
      @object = object
    end

    allowed_methods.each do |sym|
      define_method sym do
        r = @object.send sym
        # You can pass an array of objects to Liquid but not another type of collection
        if r.is_a?(ActiveRecord::Relation)
          r.to_a
        else
          r
        end
      end
    end
  end
end