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

added Protobuf::Message#[]=(key,val), Protobuf::Message#to_hash #25

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

maiha
Copy link
Contributor

@maiha maiha commented Jan 29, 2018

This PR adds #[]= and #to_hash those provide runtime meta programming.

usecase of []=

module Protobuf::Message
  def merge(hash)
    hash.each do |k,v|
      self[k] = v
...

usecase of to_hash

require "json"

struct User
  include Protobuf::Message
  contract_of "proto2" do
    required :user    , :string, 1
    optional :password, :string, 2
  end
end

record FilterParameter, keys : Array(String) do
  def apply(hash)
    hash.dup.tap{|h|
      keys.each{|k| h[k] = "[FILTERED]" if h.has_key?(k)}
    }
  end
end
pb = User.new("maiha", "1234")
pb.to_hash         # => {"user" => "maiha", "password" => "1234"}
pb.to_hash.to_json # => {"user":"maiha","password":"1234"}

secure = FilterParameter.new(["password"])
secure.apply(pb.to_hash) # => {"user" => "maiha", "password" => "[FILTERED]"}

Best regards,

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

Successfully merging this pull request may close these issues.

1 participant