Sha256: a173b555e5b5d5c5e8cb41cd2236ce94d5c2a3305c97b4bef084b3f01b30fb0b

Contents?: true

Size: 1.21 KB

Versions: 30

Compression:

Stored size: 1.21 KB

Contents

module Locomotive
  module Steam
    module Liquid
      module Filters
        module Json

          def json(input, fields = [])
            if fields && fields.is_a?(String)
              fields = fields.split(',').map(&:strip)
            end

            if input.respond_to?(:each)
              '[' + input.map do |object|
                fields.size == 1 ? object[fields.first].to_json : object_to_json(object, fields)
              end.join(',') + ']'
            else
              object_to_json(input, fields)
            end
          end

          # without the leading and trailing braces/brackets
          # useful to add a prperty to an object or an element to an array
          def open_json(input)
            if input =~ /\A[\{\[](.*)[\}\]]\Z/m
              $1
            else
              input
            end
          end

          protected

          def object_to_json(input, fields)
            if input.respond_to?(:as_json)
              options = fields.blank? ? {} : { only: fields }
              input.as_json(options).to_json
            else
              input.to_json
            end
          end

        end

        ::Liquid::Template.register_filter(Json)

      end
    end
  end
end

Version data entries

30 entries across 30 versions & 1 rubygems

Version Path
locomotivecms_steam-1.4.1 lib/locomotive/steam/liquid/filters/json.rb
locomotivecms_steam-1.4.0 lib/locomotive/steam/liquid/filters/json.rb
locomotivecms_steam-1.4.0.rc2 lib/locomotive/steam/liquid/filters/json.rb
locomotivecms_steam-1.4.0.rc1 lib/locomotive/steam/liquid/filters/json.rb
locomotivecms_steam-1.4.0.pre.rc.1 lib/locomotive/steam/liquid/filters/json.rb
locomotivecms_steam-1.3.0 lib/locomotive/steam/liquid/filters/json.rb
locomotivecms_steam-1.3.0.rc2 lib/locomotive/steam/liquid/filters/json.rb
locomotivecms_steam-1.1.2 lib/locomotive/steam/liquid/filters/json.rb
locomotivecms_steam-1.2.1 lib/locomotive/steam/liquid/filters/json.rb
locomotivecms_steam-1.3.0.rc1 lib/locomotive/steam/liquid/filters/json.rb
locomotivecms_steam-1.2.0 lib/locomotive/steam/liquid/filters/json.rb
locomotivecms_steam-1.2.0.rc3 lib/locomotive/steam/liquid/filters/json.rb
locomotivecms_steam-1.2.0.rc2 lib/locomotive/steam/liquid/filters/json.rb
locomotivecms_steam-1.2.0.rc1 lib/locomotive/steam/liquid/filters/json.rb
locomotivecms_steam-1.2.0.beta1 lib/locomotive/steam/liquid/filters/json.rb
locomotivecms_steam-1.1.1 lib/locomotive/steam/liquid/filters/json.rb
locomotivecms_steam-1.1.0 lib/locomotive/steam/liquid/filters/json.rb
locomotivecms_steam-1.1.0.rc3 lib/locomotive/steam/liquid/filters/json.rb
locomotivecms_steam-1.1.0.rc2 lib/locomotive/steam/liquid/filters/json.rb
locomotivecms_steam-1.1.0.rc1 lib/locomotive/steam/liquid/filters/json.rb