Sha256: ed733156da0ab67824f0ec0bc4715d63048b844c4635a3ac003d410565511964

Contents?: true

Size: 1.41 KB

Versions: 6

Compression:

Stored size: 1.41 KB

Contents

module Metamagic
  class Tag
    attr_reader :context, :key, :value

    def initialize(context, key, value)
      @context, @key, @value = context, key.to_s, value
      @key = @key.gsub /^[^:]+:/, "" if remove_prefix?
    end

    def to_html
      raise "#{self.class.name}#to_html must be overridden to render tag"
    end

    def sort_order
      1000
    end

    def remove_prefix?
      true
    end

    def template
      @template ||= template_for(key) || :value
    end

    def interpolated_values
      @interpolated_values ||= Array(template).map do |template|
        case template
        when Proc
          instance_exec(&template)
        when Symbol
          send(template)
        when String
          ERB::Util.html_escape(template).gsub(/:\w+/) do |key|
            ERB::Util.html_escape(send(key[1..-1]))
          end.html_safe
        else
          raise "Unknown template type #{template.class}."
        end
      end.flatten.compact.uniq.map { |value| ERB::Util.html_escape(value) }
    end

    def ==(other)
      self.class == other.class && self.key == other.key
    end

    def <=>(other)
      [sort_order, self.class.name] <=> [other.sort_order, other.class.name]
    end

    def method_missing(method, *args, &block)
      return value if method.to_s == key.gsub(":", "_") # When calling e.g. `og_image`. Used for interpolating values.
      context.send(method, *args, &block)
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
metamagic-3.1.7 lib/metamagic/tag.rb
metamagic-3.1.6 lib/metamagic/tag.rb
metamagic-3.1.5 lib/metamagic/tag.rb
metamagic-3.1.4 lib/metamagic/tag.rb
metamagic-3.1.3 lib/metamagic/tag.rb
metamagic-3.1.2 lib/metamagic/tag.rb