Last active
December 17, 2015 21:39
-
-
Save samleb/5676343 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def association_names_to_joins_argument(names) | |
| joins = names.pop | |
| joins = { names.pop => joins } until names.empty? | |
| joins | |
| end | |
| association_names_to_joins_argument([:memberships]) | |
| # => :memberships | |
| association_names_to_joins_argument([:memberships, :members]) | |
| # => { memberships: :members } | |
| association_names_to_joins_argument([:users, :posts, :comments]) | |
| # => { users: { posts: :comments } } |
Author
I like the way it reminds of Lisp's car/cdr recursive constructs, but as the method name will not be generic in this case (and is quite pretty huge), I'll rather stay with the "procedural" version, as both 3 versions have the side effect of modifying the original array.
Author
BTW, even though it won't really apply without modifications in this case, it seems like Tail Call Optimization is still not turned on by default on 2.0.0:
RUBY_VERSION
# => "2.0.0"
RubyVM::InstructionSequence.compile_option
# => {:inline_const_cache=>true,
# :peephole_optimization=>true,
# :tailcall_optimization=>false,
# :specialized_instruction=>true,
# :operands_unification=>true,
# :instructions_unification=>false,
# :stack_caching=>false,
# :trace_instruction=>true,
# :debug_level=>0}More on this on stackoverflow and this "turn by default" ticket.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not exactly the same behaviour for a single name, but a bit of inspiration maybe:
I prefer the first version and would make sure unit tests are in place ^_^