Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kodaka/a5527e0e1a5bd979ccb62f1cc9a091dd to your computer and use it in GitHub Desktop.
Save kodaka/a5527e0e1a5bd979ccb62f1cc9a091dd to your computer and use it in GitHub Desktop.
title date tags
Getting Values of Instance in Liquid Easily
2019-06-27 19:30:00 +0900
liquid
ruby

How to get values (or method? I don't care) in Liquid easily.

If you have code like those:

class Avenger
    attr_reader :name
    def instance(name)
        @name = name
    end
    def has_shield
        true
    end
end
{%- raw -%}
{% if avenger.has_shield %}
    <p>I am {{ avenger.name }}.</p>
{% endif %}
{% endraw -%}

Lite Plan A is Liquid::Drop.

class Avenger < Liquid::Drop
    # Liquid can call methods having no arguments lazily.
    ...
end

Lite Plan B is to_liquid.

class Avenger
    ...
    def to_liquid
        # but calling all of them every time
        {
            'name' => name,
            'has_shield' => has_shield
        }
    end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment