Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hash values not serialized #26

Closed
clintonb opened this issue Sep 16, 2013 · 1 comment · Fixed by #27
Closed

Hash values not serialized #26

clintonb opened this issue Sep 16, 2013 · 1 comment · Fixed by #27
Labels

Comments

@clintonb
Copy link
Contributor

The values of exposed hashes are not serialized. In the example below, a call to Person.serizable_hash() yields a hash with the key 'r:address' pointing to an Address entity instead of serializable_hash of the Address entity object.

require 'grape_entity'

class Address < Grape::Entity
  expose :street
  expose :city
end

class Person < Grape::Entity
  expose :name

  expose :_embedded do |person|
    {
      'r:address' => Address.new(person.address),
    }
  end
end

The solution I have come up with (and will PR shortly) is to update Grape::Entity.serializable_hash by adding a check for for Hash similar to what is done for Array:

def serializable_hash(runtime_options = {})
      return nil if object.nil?
      opts = options.merge(runtime_options || {})
      exposures.inject({}) do |output, (attribute, exposure_options)|
        if (exposure_options.has_key?(:proc) || object.respond_to?(attribute)) && conditions_met?(exposure_options, opts)
          partial_output = value_for(attribute, opts)
          output[key_for(attribute)] =
            if partial_output.respond_to? :serializable_hash
              partial_output.serializable_hash(runtime_options)
            elsif partial_output.kind_of?(Array) && !partial_output.map {|o| o.respond_to? :serializable_hash}.include?(false)
              partial_output.map {|o| o.serializable_hash}
            elsif partial_output.kind_of?(Hash)
              # Serialize exposed hashes
              partial_output.each do |key, value|
                partial_output[key] = value.serializable_hash if value.respond_to? :serializable_hash
              end
            else
              partial_output
            end
        end
        output
      end
    end

If there are suggestions for alternatives or improvements, or reasons why this functionality should not be included, please present them.

@dblock
Copy link
Member

dblock commented Sep 16, 2013

Seems like a legit bug.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants