- Aug 2021
-
www.ruby-lang.org www.ruby-lang.org
-
3. The no-keyword-arguments syntax (**nil) is introduced You can use **nil in a method definition to explicitly mark the method accepts no keyword arguments. Calling such methods with keyword arguments will result in an ArgumentError. (This is actually a new feature, not an incompatibility)
-
This is useful to make it explicit that the method does not accept keyword arguments. Otherwise, the keywords are absorbed in the rest argument in the above example.
-
If you extend a method to accept keyword arguments, the method may have incompatibility as follows: # If a method accepts rest argument and no `**nil` def foo(*args) p args end # Passing keywords are converted to a Hash object (even in Ruby 3.0) foo(k: 1) #=> [{:k=>1}] # If the method is extended to accept a keyword def foo(*args, mode: false) p args end # The existing call may break foo(k: 1) #=> ArgumentError: unknown keyword k
-
If your code doesn’t have to run on Ruby 2.6 or older, you may try the new style in Ruby 2.7. In almost all cases, it works. Note that, however, there are unfortunate corner cases as follows:
-
Ruby 2.6 or before themselves have tons of corner cases in keyword arguments.
-
You need to explicitly delegate keyword arguments. def foo(*args, **kwargs, &block) target(*args, **kwargs, &block) end
-
you can use the new delegation syntax (...) that is introduced in Ruby 2.7. def foo(...) target(...) end
-
-
ruby2_keywords allows you to run the old style even in Ruby 2.7 and 3.0.
-
Will my code break on Ruby 2.7? A short answer is “maybe not”. The changes in Ruby 2.7 are designed as a migration path towards 3.0. While in principle, Ruby 2.7 only warns against behaviors that will change in Ruby 3, it includes some incompatible changes we consider to be minor. See the “Other minor changes” section for details. Except for the warnings and minor changes, Ruby 2.7 attempts to keep the compatibility with Ruby 2.6. So, your code will probably work on Ruby 2.7, though it may emit warnings. And by running it on Ruby 2.7, you can check if your code is ready for Ruby 3.0.
-
However, this style is not recommended in new code, unless you are often passing a Hash as a positional argument, and are also using keyword arguments
Tags
- incompatible
- unfortunate
- ruby: keyword arguments
- newer/better ways of doing things
- being explicit
- edge cases
- Ruby
- package/tool to help with transition
- good/preferred/recommended behavior
- Ruby 3
- argument delegation
- new feature
- good example
- not:
- backwards compatible
- ruby: ArgumentError
- good explanation
Annotators
URL
-
-
api.rubyonrails.org api.rubyonrails.org
Tags
Annotators
URL
-
- Jul 2021
-
deveiate.org deveiate.org
-
"balance".en.synset( :verb )
-
-
Tags
Annotators
URL
-
-
Tags
Annotators
URL
-
-
stackoverflow.com stackoverflow.com
-
You can do this elegantly with throw/catch, like this:
-
In most languages, there is no clean equivalent for breaking out of a recursive algorithm that uses a recursive function. In Ruby, though, there is!
-
it's much faster—the stack frame does not have to be carried along the "thrown symbol", and no object is created. Lightweight nonlinear flow control.
-
Throw it's a more elegant way to use an exception-like system as a control flow.
-
-
stackoverflow.com stackoverflow.com
-
I think that it's nonsense not to have a method that just gives -1 or +1. Even BASIC has such a function SGN(n). Why should we have to deal with Strings when it's numbers we want to work with. But's that's just MHO.
-
-
test-prof.evilmartians.io test-prof.evilmartians.ioTestProf1
-
github.com github.com
Tags
Annotators
URL
-
- Jun 2021
-
graphql-ruby.org graphql-ruby.org
-
With GraphQL-Ruby, it’s possible to hide parts of your schema from some users. This isn’t exactly part of the GraphQL spec, but it’s roughly within the bounds of the spec.
-
-
evilmartians.com evilmartians.com
-
prepend(Module.new do
-
A lot of projects leveraging CDP appeared since then, including the most well-known one—Puppeteer, a browser automation library for Node.js. What about the Ruby world? Ferrum, a CDP library for Ruby, although being a pretty young one, provides a comparable to Puppeteer experience. And, what’s more important for us, it ships with a companion project called Cuprite—a pure Ruby Capybara driver using CDP.
-
-
github.com github.com
-
github.com github.com
-
gitlab.com gitlab.com
-
naildrivin5.com naildrivin5.com
-
It also makes it hard to centralize type coercions and default values.
-
-
It’s easy to create bugs because the environment is a somewhat degenerate settings database.
-
Most programming languages vend environment variables as strings. This leads to errors like so:
-
-
github.com github.com
Tags
Annotators
URL
-
-
github.com github.com
-
github.com github.com
Tags
Annotators
URL
-
-
www.gertgoet.com www.gertgoet.com
-
Note: as for setting boolean variables: not only are true/false and 0/1 acceptable values, but also T/F and on/off. Thanks, coercible!
-
-
-
github.com github.com
-
-
You could also opt to extend your Rails configuration object: Envy.init use: MyApp::Application.config MyApp::Application.config.my_variable # => ...
-
-
github.com github.com
-
Why does test suite performance matter? First of all, testing is a part of a developer's feedback loop (see @searls talk) and, secondly, it is a part of a deployment cycle.
-
-
github.com github.com
-
-
using RSpec::Parameterized::TableSyntax where(:a, :b, :answer) do 1 | 2 | 3 5 | 8 | 13 0 | 0 | 0 end
-
-
bugs.ruby-lang.org bugs.ruby-lang.org
-
bugs.ruby-lang.org bugs.ruby-lang.org
-
Same feature in TypeScript¶ It's worth mentioning that other languages have a shortcut for assignment var assignment directly from constructor parameters. So it seems especially painful that Ruby, despite being so beautifully elegant and succinct in other areas, still has no such shortcut for this. One of those other languages (CoffeeScript) is dead now, but TypeScript remains very much alive and allows you to write this (REPL): class Foo { constructor(public a:number, public b:number, private c:number) { } } instead of this boilerplate: class Foo { constructor(a, b, c) { this.a = a; this.b = b; this.c = c; } } (The public/private access modifiers actually disappear in the transpiled JavaScript code because it's only the TypeScript compiler that enforces those access modifiers, and it does so at compile time rather than at run time.) Further reading: https://www.typescriptlang.org/docs/handbook/2/classes.html#parameter-properties https://basarat.gitbook.io/typescript/future-javascript/classes#define-using-constructor https://kendaleiv.com/typescript-constructor-assignment-public-and-private-keywords/ I actually wouldn't mind being able to use public/private modifiers on instance var parameters in Ruby, too, but if we did, I would suggest making that be an additional optional shortcut (for defining accessor methods for those instance vars) that builds on top of the instance var assignment parameter syntax described here. (See more detailed proposal in #__.) Accessors are more of a secondary concern to me: we can already define accessors pretty succinctly with attr_accessor and friends. The bigger pain point that I'm much more interested in having a succinct shortcut for is instance var assignment in constructors. initialize(@a, @b, @c) syntax¶ jsc (Justin Collins) wrote in #note-12: jjyr (Jinyang Jiang) wrote: I am surprised this syntax has been repeatedly requested and rejected since 7 years ago. ... As someone who has been writing Ruby for over 10 years, this syntax is exactly that I would like. I grow really tired of writing def initialize(a, b, c) @a = a @b = b @c = c end This would be perfect: def initialize(@a, @b, @c) end I'm a little bit sad Matz is against this syntax, as it seems so natural to me. Me too!! I've been writing Ruby for over 15 years, and this syntax seems like the most obvious, simple, natural, clear, unsurprising, and Ruby-like. I believe it would be readily understood by any Rubyist without any explanation required. Even if you saw it for the first time, I can't think of any way you could miss or misinterpret its meaning: since @a is in the same position as a local variable a would normally be, it seems abundantly clear that instead of assigning to a local variable, we're just assigning to the variable @a instead and of course you can reference the @a variable in the constructor body, too, exactly the same as you could with a local variable a passed as an argument. A workaround pattern¶ In the meantime, I've taken to defining my constructor and list of public accessors (if any) like this: attr_reader \ :a, :b def new( a, b) @a, @b = a, b end ... which is still horrendously boilerplatey and ugly, and probably most of you will hate — but by lining up the duplicated symbols into a table of columns, I like that I can at least more easily see the ugly duplication and cross-check that I've spelled them all correctly and handled them all consistently. :shrug: Please??¶ Almost every time I write a new class in Ruby, I wish for this feature and wonder if we'll ever get it. Can we please?
-
I am not sure if this is an improvement. To me it does not seem very pretty. Of course I am biased since I also prefer () in method definitions if they have arguments; although I think it is fine that ruby does not mind omitting the (). For my brain, I like the () for visual separation.
-
-
bugs.ruby-lang.org bugs.ruby-lang.org
-
bugs.ruby-lang.org bugs.ruby-lang.org
-
github.com github.com
-
-
github.com github.com
-
stackoverflow.com stackoverflow.com
-
When defining accessors in Ruby, there can be a tension between brevity (which we all love) and best practice.
-
in languages (like JavaScript and Java) where external objects do have direct access to instance vars
-
But what's the matter with "raw" instance variables? They are internal to your instance; the only code that will call them by name is code inside pancake.rb which is all yours. The fact that they start with @, which I assume made you say "blech", is what makes them private. Think of @ as shorthand for private if you like.
I agree / like that:
@
is just shorthand forprivate
.But OP clarified in a comment that the
@
itself is not what they disliked: it was the accessing data directly instead of going through an accessor method.The raw variable is the implementation, the accessor is the interface. Should I ignore the interface because I'm internal to the instance?
-
class << Object def private_accessor(*names) names.each do |name| attr_accessor name private "#{name}=" end end end
-
Setting an instance variable by going through a setter is good practice, and using two access modifiers is the way to accomplish that for a read-only instance variable
Tags
- JavaScript
- best practices
- concise
- programming: access modifiers (public/private)
- Ruby
- brevity
- programming languages: external objects have direct access to instance variables
- Ruby: instance variables
- JavaScript: private instance accessors
- safety (programming)
- accessors
- metaprogramming
- idiomatic Ruby
- balance
- I agree
- convention
- languages: differences
- encapsulation
Annotators
URL
-
-
stackoverflow.com stackoverflow.com
-
I don't think this warrants adding to the Array class, since it's not generalizable to all the types that Arrays can contain.
You could say the same thing about
Array#sort
. It can cause an error if elements of the array aren't all of the same type/shape. Just make sure it's safe to use first, and thenArray#sort
,Array#sum
,Array#average
, ... are all quite handy and useful to have on Array class. -
That's not exactly Symbol#to_proc conversion — it's part of the inject interface, mentioned in the documentation. The to_proc operator is &
-
instance_eval { reduce(:+) / size.to_f }
-
I don't think it is too clever. I think it solves the problem idiomatically. I.e., it uses reduce, which is exactly correct. Programmers should be encouraged to understand what is correct, why it is correct, and then propagate. For a trivial operation like average, true, one doesn't need to be "clever". But by understanding what "reduce" is for a trivial case, one can then start applying it to much more complex problems. upvote.
-
Thanks, this was just what I was looking for! This is a perfect appropriate use of instance_eval. I do not understand the nay-sayers. If you already have your array in a variable, then sure, a.reduce(:+) / a.size.to_f is pretty reasonable. But if you want to "in line" find the mean of an array literal or an array that is returned from a function/expression — without duplicating the entire expression ([0,4,8].reduce(:+) / [0,4,8].length.to_f, for example, is abhorrent) or being required to assign to a local, then instance_eval option is a beautiful, elegant, idiomatic solution!!
-
instance_eval is analogous to using tap, yield_self, … when you are dealing with a chain of method calls: do use it whenever it's appropriate and helpful! And in this case, I absolutely believe that it is.
-
instance_eval lets you run the code while only specifying a once, so it can be chained with other commands. I.e. random_average = Array.new(10) { rand(10) }.instance_eval { reduce(:+) / size.to_f } instead of random = Array.new(10) { rand(10) }; random_average = random.reduce(:+) / random.size
-
I don't know, using instance_eval this way just seems weird, and it has a lot of gotchas associated with it that make this approach a bad idea, IMO. (For example, if you tried to access and instance variable or a method on self inside that block, you'd run into problems.) instance_eval is more for metaprogramming or DSL.
But that's exactly when/why you'd use it: to make
self
refer to the instance! Just learn that and you'll be fine. You can still access locals from outside the block. And if you need to access instance variables/methods of a different instance, then sure, it's probably a sign you shouldn't be using instance_eval here. -
Or if you're looking for a core extension that adds this to the Array class, I'd recommend the facets gem (require 'facets/array/average'). Then you can just do array.average. And, from looking at the source, it turns out they do the exact same thing as the instance_eval approach above. The only difference is that it's implemented as a method—which of course already has self pointing to itself—instead of a block): def average; return nil if empty?; reduce(:+) / length.to_f; end Main advantage of this is that it's even more concise/readable and it handles the empty? case.
Tags
- example of: reduce
- distinction
- concise
- Ruby: to_proc
- ruby: arrays
- gem: facets
- ruby library
- Ruby
- easy to falsely assume
- one-liners
- clever
- my comments
- where it shines / best application
- appropriateness
- analogy
- recommended software
- not:
- I disagree
- recommended library
- idiomatic Ruby
- reduce
- too clever
- idiomatic (programming)
- clever solution
- appropriate use case
- I agree
- generalizable
- I have a differing opinion
- Ruby: instance_eval
Annotators
URL
-
-
github.com github.com
-
Gary Foster has provided a script to migrate to Pundit.
-
-
developer.mozilla.org developer.mozilla.orgProxy1
-
get: function(target, prop, receiver) { return "world"; }
-
-
- May 2021
-
stackoverflow.com stackoverflow.com
-
Because constants in Ruby aren't meant to be changed, Ruby discourages you from assigning to them in parts of code which might get executed more than once, such as inside methods.
-
- Apr 2021
-
stackoverflow.com stackoverflow.com
-
If there are some pipe between these commands, you need to flush stdout. for example: script -q /dev/null commands... | ruby -ne 'print "....\n";STDOUT.flush'
-
-
stackoverflow.com stackoverflow.com
-
It seems inelegant to me to split this into two different modules, one to include, the other to extend.
the key thing (one of them) to understand here is that: class methods are singleton methods
-
Another possible solution would be to use a class Common instead of a module. But this is just a workaround.
-
Trust this answer. This is a very common idiom in Ruby, solving precisely the use case you ask about and for precisely the reasons you experienced. It may look "inelegant", but it's your best bet.
-
-
gist.github.com gist.github.com
-
Apparently when you create a subclass, that subclass's singleton class has # its superclass's singleton class as an ancestor.
This is a good thing. It allows class methods to be inherited by subclasses.
-
at least in recent versions of Ruby, calling ancestors on the singleton class does show the other singleton classes.
-
I played around with something to give me the list of receivers for any Ruby object in my introspection gem. If you load the "introspection/receivers" file you get a method #receivers on any object which gives you the whole receiver chain.
-
-
github.com github.com
-
first sighting: this file referenced by https://hyp.is/ZD-z8px8Eeue0ws8rEMsrw/gist.github.com/cowboyd/1642793
-
if Gem::Version.new(RUBY_VERSION) < Gem::Version.new('2.1.0')
-
-
github.com github.com
Tags
Annotators
URL
-
-
medium.com medium.com
-
I wish to define methods within the class they belong to. Using class << self demonstrates that approach clearly — we are defining methods within the actual singleton class scope.
-
Class Methods Are Singleton MethodsSince in Ruby classes are objects as well, class methods are merely methods defined on a specific instance of Class.
-
- Mar 2021
-
www.rubymotion.com www.rubymotion.com
-
Not enjoying Xcode, Amir used RubyMotion instead. Amir had real-world experience with Xcode and Objective-C, but didn't like it at all. Amir also has a Ruby background and went with RubyMotion to build A Dark Room. The command-line interface, the testing framework, the gems libraries and the CocoaPods integration and the freedom to use any text editor contributed to his decision.
-
-
github.com github.com
-
ProMotion is a RubyMotion gem that makes iOS development more like Ruby and less like Objective-C.
-
-
rawgit.com rawgit.com
-
github.com github.com
-
# Parallel Ruby universes ("Rubyverses") - A proposed interface for # parallel, "semi-private" method or method-and-data spaces via # "closely associated" objects.
-
-
github.com github.com
-
possibly similar solution to ActiveSupport::Concern?
-
-
bugs.ruby-lang.org bugs.ruby-lang.org
-
A proposal to specify the path for bury with classes as values of a hash arg: {}.bury(users: Array, 0 => Hash, name: Hash, something: 'Value') # {user: [{name: {something: 'Value'}]} So all absent nodes could be created via klass.new
Didn't understand it at first, but now I think it's a pretty clever/decent solution.
Just a bit more verbose than one might like...
At first I had reservations about the fact that this requires you to pass a hash ... or rather, once you start using a hash as your "list", you can't just "switch back" to an array (a "problem" I've noticed in RSpec, where you have some tags that are symbols, and some that are hashes: you have to list the symbols first:
describe 'thing', :happy_path, driver: :chrome
):{}.bury(users: Array, 0, 'Value')
But I think that's okay in practice. Just use a hash for all "elements" in your list:
{}.bury(users: Array, 0 => 'Value')
-
I think the issues/problems specified in the comments are not present with a Hash-only implementation. :) I would be supportive of re-considering this feature just for use with a Hash, where I believe 80% of the real-life use cases would (and do) exist. I have encountered this need before in the wild, but not with Arrays.
-
In fact, I'm only here because it seems like something one would 'expect' ruby already to do.
Tags
- objects/hashes
- ruby: core extensions: hash
- expected library/language to have feature but is missing
- Ruby
- solving/handling specific case instead of the general case because general solution would be too hard/complex
- interesting approach/solution
- I agree
- solving/handling the general case
- can't support everything / all cases
- Ruby: core
- simple solution
Annotators
URL
-
-
github.com github.com
-
No docs?!
[ Some docs here; First saw it here: ] https://bugs.ruby-lang.org/issues/11747#note-7
-
-
stackoverflow.com stackoverflow.com
-
can you break this, thouugh? like can you override kind_of? but not is_a?
-
It just reads better sometimes. Think @honda.kind_of? Car and @person.is_a? Administrator, Ruby's all about the aesthetics.
-
As to why both is_a? and kind_of? exist: I suppose it's part of Ruby's design philosophy. Python would say there should only be one way to do something; Ruby often has synonymous methods so you can use the one that sounds better. It's a matter of preference.
-
-
trailblazer.to trailblazer.to
-
definitely less rough to work with than Devise
-
-
github.com github.com
-
github.com github.com
-
#!/usr/bin/env ruby txmt_param = ARGV[0] txmt_path = txmt_param.match("%2F.*&").to_s txmt_path = txmt_path [0...-1] txmt_path_slashed = txmt_path.gsub("%2F","/") txmt_line = txmt_param.match("&line=.*").to_s txmt_line = txmt_line [6..txmt_line.length] vim_params = Array.new vim_params = "--remote-tab-silent" vim_params << " +#{txmt_line}" if txmt_line vim_params << " #{txmt_path_slashed}"
-
-
github.com github.com
-
dry-rb.org dry-rb.org
-
Dry::Types::Undefined
Cool! I workaround for the fact that Ruby has no undefined type distinct from nil.
-
-
github.com github.com
-
how to have validations in model and some in contract/form object without duplicating
-
-
github.com github.com
-
And no need to walk backwards through all these strings which is surprisingly inefficient in Ruby.
-
-
opalrb.com opalrb.com
-
Opal is a Ruby to JavaScript source-to-source compiler. It comes packed with the Ruby corelib you know and love. It is both fast as a runtime and small in its footprint.
-
-
hyperstack.org hyperstack.org
-
Notice that the HTML elements (BUTTON, DIV, etc.) are in CAPS. We know this is bending the standard Ruby style rules slightly, but we think it reads better this way.
-
-
we used `backticks` to jump into native Javascript to use moment.js
In regular Ruby, `` executes in a shell, but obviously there is no shell of that sort in JS, so it makes sense that they could (and should) repurpose that syntax for something that makes sense in context of JS -- like running native JavaScript -- prefect!
-
Hyperstack gives you full access to the entire universe of JavaScript libraries and components directly within your Ruby code.Everything you can do in JavaScript is simple to do in Ruby; this includes passing parameters between Ruby and JavaScript and even passing Ruby methods as JavaScript callbacks.There is no need to learn JavaScript, all you need to understand is how to bridge between JS and Ruby.
-
-
github.com github.com
-
faastruby.io faastruby.io
-
One day last August 2018, I stumbled upon an online petition that sparked my curiosity - We Want Serverless Ruby. At that time, none of the major cloud providers had first-class support for Ruby in their serverless products. There were ~1400 devs signing that petition, and I wondered if there was something about Ruby that made it unsuitable for FaaS. I decided to roll the sleeves and start building what would be the first PoC of faastRuby.
Tags
Annotators
URL
-
-
github.com github.com
-
-
Using ::delegates works exactly like the Forwardable module in Ruby, with one bonus: It creates the accessors in a module, allowing you to override and call super in a user module or class.
-
Uber::Option implements the pattern of taking an option, such as a proc, instance method name, or static value, and evaluate it at runtime without knowing the option's implementation.
-
-
github.com github.compry/pry1
-
you can use the wtf? command to display a few lines of the backtrace for the most recent exception
-
-
trailblazer.to trailblazer.to
-
The absence of a method name here is per design: this object does only one thing, and hence what it does is reflected in the class name.
-
-
trailblazer.to trailblazer.to
-
There’s no additional logic from Trailblazer happening here. The function returns a well-defined hash which is passed as an argument to step.
-
- Feb 2021
-
github.com github.com
-
It will return the result as a Dry::Monads::Result object which can be either successful or failure.
-
-
trailblazer.to trailblazer.to
-
# Yes, you can use lambdas as steps, too! step ->(ctx, params:, **) { params.is_a?(Hash) }
-
Keyword arguments allow to define particular parameters as required. Should the parameter be missing, they also provide a way to set a default value. This is all done with pure Ruby.
-
a task in an activity can be any callable Ruby object
-
Your actual logic happens in tasks, the labeled boxes. A task may be any callable Ruby object, an instance method or even another activity.
-
Trailblazer is an architectural pattern that comes with Ruby libraries to implement that pattern.
-
-
github.com github.com
-
(match = html.match(/<meta name="csp-nonce" content="([^"]*)"/)) && match[1] html[/<meta name="csp-nonce" content="([^"]*)"/, 1]
Tags
Annotators
URL
-
-
trailblazer.to trailblazer.to
-
Please note that the actual task doesn’t have to be a proc! Use a class, constant, object, as long as it exposes a #call method it will flow.
-
You may use keyword arguments in your filters for type safety and better readable code.
-
-
www.morozov.is www.morozov.is
-
include Dry::Monads::Do.for(:call)
-
bind applies unwrapped Success value to the block, which should return a Result object. No-op on Failure
-
-
-
dry-rb.org dry-rb.org
-
github.com github.com
-
github.com github.com
-
Operations define the flow of their logic using the DSL and implement the particular steps with pure Ruby.
Tags
Annotators
URL
-
-
trailblazer.to trailblazer.to
-
Yes, Trailblazer is adding new abstractions and concepts and they are different to the 90s-Ruby, but now, at the latest, it becomes obvious how this improves the developing process. We’re no longer talking in two-dimensional method stack traces or byebug hoops, the language and conception is changing to the actual higher level code flow, to activities sitting in activities structured into smaller step units.
-
-
github.com github.com
-
There are times where it is useful to know whether a value was passed to run or the result of a filter default. In particular, it is useful when nil is an acceptable value.
Yes! An illustration in ruby:
main > h = {key_with_nil_value: nil} => {:key_with_nil_value=>nil} main > h[:key_with_nil_value] => nil main > h[:missing_key] # this would be undefined in JavaScript (a useful distinction) rather than null, but in Ruby it's indistinguishable from the case where a nil value was actually explicitly _supplied_ by the caller/user => nil # so we have to check for "missingness" ("undefinedness"?) differently in Ruby main > h.key?(:key_with_nil_value) => true main > h.key?(:missing_key) => false
This is one unfortunate side effect of Ruby having only
nil
and no built-in way to distinguish betweennull
andundefined
like in JavaScript.
-
-
stackoverflow.com stackoverflow.com
-
The problem is that you what you want is actually not de-structuring at all. You’re trying to go from 'arg1', { hash2: 'bar', hash3: 'baz' }, { hash1: 'foo' } (remember that 'arg1', foo: 'bar' is just shorthand for 'arg1', { foo: 'bar' }) to 'arg1', { hash1: 'foo', hash2: 'bar', hash3: 'baz' } which is, by definition, merging (note how the surrounding structure—the hash—is still there). Whereas de-structuring goes from 'arg1', [1, 2, 3] to 'arg1', 1, 2, 3
-
-
-
{a: 1, b: 2, c: 3, d: 4} => {a:, b:, **rest} # a == 1, b == 2, rest == {:c=>3, :d=>4}
equivalent in javascript:
{a, b, ...rest} = {a: 1, b: 2, c: 3, d: 4}
Not a bad replacement for that! I still find javascript's syntax a little more easily readable and natural, but given that we can't use the same syntax (probably because it would be incompatible with existing syntax rules that we can't break for compatibility reasons, unfortunately), this is a pretty good compromise/solution that they've come up with.
-
-
You can rescue at the method level, but more likely you’d want to rescue at the statement level.
-
(Yay for the hashrocket resurgence!)
-
we’re going to look how improved pattern matching and rightward assignment make it possible to “destructure” hashes and arrays in Ruby 3—much like how you’d accomplish it in, say, JavaScript
Tags
- equivalent/analogous/alternative ways to do something between 2 libraries/languages/etc.
- JavaScript
- object destructuring
- ruby
- ruby: hash object destructuring
- feature parity
- scope (programming)
- resurgence
- good example
- improvement
- funny
- error/exception handling
- operators
- backwards compatible
- constant evolution/improvement of software/practices/solutions
Annotators
URL
-
-
github.com github.com
-
Nevermind, I use now reform-rails
-
@adisos if reform-rails will not match, I suggest to use: https://github.com/orgsync/active_interaction I've switched to it after reform-rails as it was not fully detached from the activerecord, code is a bit hacky and complex to modify, and in overall reform not so flexible as active_interaction. It has multiple params as well: https://github.com/orgsync/active_interaction/blob/master/spec/active_interaction/modules/input_processor_spec.rb#L41
I'm not sure what he meant by:
fully detached from the activerecord I didn't think it was tied to ActiveRecord.
But I definitely agree with:
code is a bit hacky and complex to modify
-
you can do pairs.each_with_object({}) do |(multiparameter_name, value), attributes|
-
values_with_empty_parameters.each_value.all?(&:nil?) This comment has been minimized. Show comment Hide comment Copy link Quote reply egilburg on Apr 9, 2015 Contributor you can do values_with_empty_parameters.values.none? [nil, nil].none? => true Pick your reaction egilburg on Apr 9, 2015 Contributor you can do values_with_empty_parameters.values.none? [nil, nil].none? => true
Tags
- concise
- ruby
- hard to understand
- missed opportunity
- I agree
- switching/migrating to something different
- evaluating software options
- pointing out gaps/downsides/cons in competition/alternatives
- recommended option/alternative
- too complicated
- recommended software
- active_interaction
- too coupled/dependent
- flexibility
- reform (Ruby)
Annotators
URL
-
-
github.com github.com
-
Set your models free from the accepts_nested_attributes_for helper. Action Form provides an object-oriented approach to represent your forms by building a form object, rather than relying on Active Record internals for doing this.
It seems that the primary/only goal/purpose was to provide a better alternative to ActiveRecord's accepts_nested_attributes_for.
Unfortunately, this appears to be abandoned.
-
-
en.wikipedia.org en.wikipedia.org
-
Some languages like Smalltalk and Ruby only allow access via object methods
-
-
-
DSLs can be problematic for the user since the user has to manage state (e.g. am I supposed to call valid? first or update_attributes?). This is exactly why the #validate is the only method to change state in Reform.
-
I like your API here much better than reform's API.
-
reform conflates these two responsibilities into a single validate method
-
-
github.com github.com
-
Compared to existing Ruby desktop frameworks, such as Shoes, Bowline's strengths are its adherence to MVC and use of HTML/JavaScript.
-
-
-
github.com github.com
-
github.com github.com
-
Set your models free from the accepts_nested_attributes_for helper. Active Form provides an object-oriented approach to represent your forms by building a form object, rather than relying on Active Record internals for doing this.
-
- Jan 2021
-
github.com github.com
-
github.com github.com
-
This allows you to execute multiple scripts in parallel.
-
GIL free JavaScript execution The Ruby Global interpreter lock is released when scripts are executing
-
-
www.mrtemplates.com www.mrtemplates.com
-
Premailer is written in Ruby
Tags
Annotators
URL
-
-
github.com github.com
Tags
Annotators
URL
-
- Dec 2020
-
ttytoolkit.org ttytoolkit.org
-
Terminal Apps The Easy Way
A ruby toolkit for building terminal apps. Components for handling common (and uncommon) needs.
-
-
github.com github.com
-
json.(
I don't care what the Rubocop style guide says about this; this is nicer and cleaner than typing
json.call(...)
.
-
-
idiosyncratic-ruby.com idiosyncratic-ruby.com
Tags
Annotators
URL
-
-
github.com github.com
Tags
Annotators
URL
-
- Nov 2020
-
guides.rubyonrails.org guides.rubyonrails.org
-
You can use the match method with the :via option to match multiple verbs at once:
-
-
github.com github.com
-
Dart Sass has replaced Ruby Sass as the canonical implementation of the Sass language.
-
- Oct 2020
-
github.com github.com
-
Probably wouldn't work for capybara-based tests where it forks a different process for the web server?
-
-
engineering.appfolio.com engineering.appfolio.com
-
-
optcarrot, is a headless NES emulator that the Ruby core team are using as a CPU-intensive optimization target.
-
-
github.com github.com
-
StackProf.start(mode: :cpu) StackProf.stop StackProf.results('/tmp/some.file')
-
-
-
stackoverflow.com stackoverflow.com
-
However, if perform was creating threads and you ended up with closures inside perform, then you could end up with several threads referencing the same local variables captured through the closures. So you do have to be careful about scope issues when you create threads but you don't have to worry about it when dealing with simple methods that only work with local variables
Однако, если выполнение создавало потоки, и вы закончили с замыканиями внутри выполнения, тогда вы могли бы получить несколько потоков, ссылающихся на одни и те же локальные переменные, захваченные с помощью замыканий. Таким образом, вы должны быть осторожны с проблемами области при создании потоков, но вам не нужно беспокоиться об этом при работе с простыми методами, которые работают только с локальными переменными.
-
The local variables, such as your hash, are local to the particular invocation of the surrounding method. If two threads end up calling perform at the same time, then each call will get its own execution context and those won't overlap unless there are shared resources involved: instance variables (@hash), class variables (@@hash), globals ($hash), ... can cause concurrency problems. There's nothing to worry about thread-wise with something simple like your perform.
Локальные переменные, такие как ваш хэш, являются локальными для конкретного вызова окружающего метода. Если два потока вызывают выполнение одновременно, то каждый вызов получит свой собственный контекст выполнения, и они не будут перекрываться, если не задействованы общие ресурсы: переменные экземпляра (@hash), переменные класса (@@ hash), глобальные переменные. ($ hash), ... может вызвать проблемы параллелизма. Не нужно беспокоиться о потоковой передаче с чем-то простым, например, с вашей работой.
-
- Sep 2020
- Aug 2020
-
bugs.ruby-lang.org bugs.ruby-lang.org
-
It's unfortunate, but I can understand why they decided this way.
-
-
www.onthegosystems.com www.onthegosystems.com
-
Ruby is the programming language used in Translation Proxy. For Sarah, Object Oriented Design “done the Ruby way” is so enjoyable and is the part of her work that she likes most.
-
- Jul 2020
-
-
Ruby has some really nice libraries for working with linked data. These libraries allow you to work with the data in both a graph and resource-oriented fashion, allowing a developer to use the techniques that best suit his or her use cases and skills.
-
-
bugs.ruby-lang.org bugs.ruby-lang.org
-
bugs.ruby-lang.org bugs.ruby-lang.org
-
bugs.ruby-lang.org bugs.ruby-lang.org
-
bugs.ruby-lang.org bugs.ruby-lang.org
-
api.rubyonrails.org api.rubyonrails.org
-
Time.current returns said timestamp, and Time.now its equivalent in the system time zone.
-
-
ruby-doc.org ruby-doc.org
-
Since Ruby 1.9.2, Time implementation uses a signed 63 bit integer, Bignum or Rational. The integer is a number of nanoseconds since the Epoch which can represent 1823-11-12 to 2116-02-20. When Bignum or Rational is used (before 1823, after 2116, under nanosecond), Time works slower as when integer is used.
Tags
Annotators
URL
-
-
bugs.ruby-lang.org bugs.ruby-lang.org
-
There is a usability problem here, it's basically impossible to read the output of Time#inspect in such a case, even though the input was readable.
-
So, which is better? t.inspect # => "2007-11-01 15:25:00 8483885939586761/68719476736000000 UTC" t.inspect # => "2007-11-01 15:25:00.123456789000000004307366907596588134765625 UTC"
-
-
github.com github.com
-
sourcediving.com sourcediving.com
-
Introducing Module#const_source_locationUsing Method#source_location made finding the location of any method fairly easy. Unfortunately, there wasn’t an equivalent for constants. This meant that unless the constant you needed to find was defined in your codebase, finding its source location was not easy.
-
-
blog.toshima.ru blog.toshima.ru
-
To stop emitting the warnings, just add RUBYOPT=-W:no-deprecated.
-
-
www.ruby-lang.org www.ruby-lang.org
-
Enumerable#tally is added. It counts the occurrence of each element. ["a", "b", "c", "b"].tally #=> {"a"=>1, "b"=>2, "c"=>1}
-
Enumerator::Lazy#eager is added. It generates a non-lazy enumerator from a lazy enumerator.
-
-
bugs.ruby-lang.org bugs.ruby-lang.org
-
It does change it, but it makes it much simpler in my opinion. It is basically "the receiver is statically the explicit literal special variable self or implicit." This gets rid of the current exception for private writer methods (self.foo = bar).
Tags
Annotators
URL
-
-
bugs.ruby-lang.org bugs.ruby-lang.org
-
I guess much like Range literals in general, it's often needed to have parens around them.
Tags
Annotators
URL
-