Sha256: 2d3b64ce28ba7533578d32822e6773f6141b04e44d5e1fcff9367cbf4f1fe5b8

Contents?: true

Size: 1.29 KB

Versions: 17

Compression:

Stored size: 1.29 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.is_a?(Hash)
              object_to_json(input, fields)
            elsif 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

17 entries across 17 versions & 1 rubygems

Version Path
locomotivecms_steam-1.8.0.alpha2 lib/locomotive/steam/liquid/filters/json.rb
locomotivecms_steam-1.8.0.alpha1 lib/locomotive/steam/liquid/filters/json.rb
locomotivecms_steam-1.7.1 lib/locomotive/steam/liquid/filters/json.rb
locomotivecms_steam-1.7.0 lib/locomotive/steam/liquid/filters/json.rb
locomotivecms_steam-1.6.1 lib/locomotive/steam/liquid/filters/json.rb
locomotivecms_steam-1.6.0 lib/locomotive/steam/liquid/filters/json.rb
locomotivecms_steam-1.6.0.rc1 lib/locomotive/steam/liquid/filters/json.rb
locomotivecms_steam-1.6.0.beta1 lib/locomotive/steam/liquid/filters/json.rb
locomotivecms_steam-1.5.3 lib/locomotive/steam/liquid/filters/json.rb
locomotivecms_steam-1.5.2 lib/locomotive/steam/liquid/filters/json.rb
locomotivecms_steam-1.5.1 lib/locomotive/steam/liquid/filters/json.rb
locomotivecms_steam-1.5.0 lib/locomotive/steam/liquid/filters/json.rb
locomotivecms_steam-1.5.0.rc1 lib/locomotive/steam/liquid/filters/json.rb
locomotivecms_steam-1.5.0.rc0 lib/locomotive/steam/liquid/filters/json.rb
locomotivecms_steam-1.5.0.beta3 lib/locomotive/steam/liquid/filters/json.rb
locomotivecms_steam-1.5.0.beta2 lib/locomotive/steam/liquid/filters/json.rb
locomotivecms_steam-1.5.0.beta1 lib/locomotive/steam/liquid/filters/json.rb