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

Feature idea: Hashie::Bash - the Builder Hash #229

Open
maxlinc opened this issue Sep 30, 2014 · 1 comment
Open

Feature idea: Hashie::Bash - the Builder Hash #229

maxlinc opened this issue Sep 30, 2014 · 1 comment

Comments

@maxlinc
Copy link
Contributor

maxlinc commented Sep 30, 2014

I'm working on a Swagger library for ruby. I wanted a Swagger::Builder so projects like grape-swagger could walk the grape DSL and build a swagger object.

I'd already described the Swagger structure as a Dash so I could load complete Swagger files. I wanted to be able to use the same definition in order to build a Swagger object, but the required constraints would get in my way, forcing me to work with a normal Hash or Mash until the object was complete.

I implemented an experimental Bash mixin so I could get around that limitation:

A Bash is a 'builder' Hash that can be used to build a

# Dash ('defined' or 'discrete' Hash). It provides a
# `build` method that turns the Bash into a Dash. It enforces
# the same constraints and coercions as a Dash except for 'required' properties,
# which are not enforced until converting to a Dash via `build`.

See the Swagger::Builder spec for an example of how a Bash-based builder would work.

This let's me keep the "discrete" behavior of a Dash - so I get immediate errors if I try to use set an undefined property. Type coercions also happen immediately, and I'll get a Hashie:: CoercionError if I use the wrong type. These errors will happen on the line where I try to make the assignment, rather than much later when I'm converting a Hash to a Dash. I don't get the property 'x' is required errors until I call swagger_builder.build, but since that's an error of omission it wouldn't have a line number anyways.

The implementation has the advantage of being self-contained - it doesn't require changes to any Hashie classes (and doesn't monkeypatch them) but it achieves this through fragile and complex metaprogramming that dynamically subclasses Dash objects. I'm creating an issue rather than a PR in the hopes that someone has an idea for a simpler implementation that updates Dash to be more Bash friendly.

@dblock
Copy link
Member

dblock commented Sep 30, 2014

I'll take a look, in the meantime I have to say that I love the "it achieves this through fragile and complex metaprogramming" :)

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

No branches or pull requests

2 participants