Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@saturnflyer
Last active May 24, 2017 20:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saturnflyer/eae091e11a0bd938de6694be96ffdb1c to your computer and use it in GitHub Desktop.
Save saturnflyer/eae091e11a0bd938de6694be96ffdb1c to your computer and use it in GitHub Desktop.
Using casting to apply different behaviors to an object for generating JSON
require 'json'
require 'casting'
module Names
def names
"names here"
end
end
module Secrets
def secrets
"secrets here"
end
end
module Redacted
def secrets
"***********"
end
end
class Jsoner
include Casting::Client
delegate_missing_methods
def as_json(*attributes)
{}.tap do |hash|
attributes.each do |att|
hash[att] = self.send(att)
end
end
end
end
empty = Jsoner.new
empty.cast_as(Casting::Null)
puts empty.as_json(:names, :secrets)
secret = Jsoner.new
secret.cast_as(Casting::Null, Secrets)
puts secret.as_json(:names, :secrets)
everything = Jsoner.new
everything.cast_as(Casting::Null, Secrets, Names)
puts everything.as_json(:names, :secrets)
names = Jsoner.new
names.cast_as(Casting::Null, Names)
puts names.as_json(:names, :secrets)
redacted = Jsoner.new
redacted.cast_as(Casting::Null, Secrets, Redacted)
puts redacted.as_json(:names, :secrets)
# This will output:
# {:names=>nil, :secrets=>nil}
# {:names=>nil, :secrets=>"secrets here"}
# {:names=>"names here", :secrets=>"secrets here"}
# {:names=>"names here", :secrets=>nil}
# {:names=>nil, :secrets=>"***********"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment