Skip to content

Instantly share code, notes, and snippets.

@hopsoft
Last active August 29, 2015 14:10
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 hopsoft/28770a03b9bd87c045b9 to your computer and use it in GitHub Desktop.
Save hopsoft/28770a03b9bd87c045b9 to your computer and use it in GitHub Desktop.
Han Transition Wrapper in Ruby
require "active_support/all"
require "forwardable"
class Transition
extend Forwardable
def_delegators :params, :to_query, :to_json
def initialize(han_transition)
@han_transition = han_transition.symbolize_keys
@params = han_transition[:params].symbolize_keys
end
def to_get
[href, to_query].join("?")
end
alias_method :to_post, :to_json
def method_missing(name, *args)
return super unless respond_to?(name)
han_transition[name.to_sym]
end
def respond_to?(name)
return true if han_transition.has_key?(name.to_sym)
super
end
private
attr_reader :han_transition, :params
end
han_transition = {
type: "hard",
name: "foobar",
href: "http://somewhere.com/api/v3/foobar",
verbs: ["GET"],
headers: [],
formats: ["json"],
params: {
foo: true,
bar: "some value",
list: [1,2,3],
obj: { nested: { deep: true } }
},
examples: {}
}
t = Transition.new(han_transition)
t.name # => "foobar"
t.to_get # => "http://somewhere.com/api/v3/foobar?bar=some+value&foo=true&list%5B%5D=1&list%5B%5D=2&list%5B%5D=3&obj%5Bnested%5D%5Bdeep%5D=true"
t.to_post # => "{\"foo\":true,\"bar\":\"some value\",\"list\":[1,2,3],\"obj\":{\"nested\":{\"deep\":true}}}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment