- Last 7 days
- Oct 2024
-
-
Is this in case a plugin used prepend SomeModule to prepend a module into this class?
hash = super if defined?(super)
Actually, I see that https://github.com/filewatcher/filewatcher-access/blob/main/lib/filewatcher/access.rb used
class SnapshotFile extend( Module.new do
Is that similar? I think so. -
lambda(&:nil?)
-
- Sep 2024
-
-
github.com github.com
-
Looks well-written, but probably not needed in a Rails project, which already has ActiveSupport for dealing with duration and periods
Tags
Annotators
URL
-
-
-
Utopia is a website generation framework which provides a robust set of tools to build highly complex dynamic websites. It uses the filesystem heavily for content and provides functions for interacting with files and directories as structure representing the website.
Tags
Annotators
URL
-
-
github.com github.com
-
drip engine for managing, creating, and performing scheduled messages sequences
Tags
Annotators
URL
-
-
bugs.ruby-lang.org bugs.ruby-lang.org
-
Here's example code which works around the lack of a ??= operator in the wild:
-
-
en.wikipedia.org en.wikipedia.org
-
In comparison, Perl/Python/Javascript, which also have the latter property, have other false-like values (0 and empty string), which make || differ from a null-coalescing operator in many more cases (numbers and strings being two of the most frequently used data types). This is what led Perl/Python/Javascript to add a separate operator while Ruby hasn't.
-
-
github.com github.com
-
However, this idiom is only an approximation, and introduces subtle bugs when we try to allow false values:
-
Ruby, as a community, unfairly discriminates against false, and it needs to stop.
-
false is a perfectly non-nil object, and you're excluding it out of convenience!
-
-
github.com github.com
-
new tag: display/view for audience
-
-
www.gertgoet.com www.gertgoet.com
-
# booleans # simple: providing any value for ENV['FORCE_SSL'] means `true`: force_ssl = !!ENV['FORCE_SSL'] # more advanced: # only when we provide 'true' will `force_ssl` become true. force_ssl = ('true' == ENV['FORCE_SSL'])
-
-
-
Looks really nice. May switch to this from Memoist. This alt is much more configurable.
Tags
Annotators
URL
-
-
github.com github.com
-
mount IndexController do # all methods will be mounted automatically, it's just an example of refinement get '/hello', :hello_world end
-
-
-
.time {|timer = Timer.new.start| ... } ⇒ Object Takes a block and returns the total time it took to execute.
-
-
socketry.github.io socketry.github.io
- Jul 2024
-
www.liberation.fr www.liberation.fr
-
Ces tribus accusaient les entreprises américaine Ruby Canyon Environmental et colombienne Masbosques d’avoir négocié la vente de crédits carbone pour leur territoire avec des personnes n’ayant pas l’autorité pour le faire
-
- May 2024
-
github.com github.com
-
github.com github.com
-
You'll need to either stop transpiling or use a Node-based transpiler, like those in jsbundling-rails and cssbundling-rails.
-
-
github.com github.com
-
# This is manual way to describe complex parameters parameter :one_level_array, type: :array, items: {type: :string, enum: ['string1', 'string2']}, default: ['string1'] parameter :two_level_array, type: :array, items: {type: :array, items: {type: :string}} let(:one_level_array) { ['string1', 'string2'] } let(:two_level_array) { [['123', '234'], ['111']] }
-
- Feb 2024
-
github.com github.com
-
Its a bit tricky because of the ambiguity of how the args get presented. You can see through the little demo the args are presented the same way whether its a straight kwargs or a hash, but the assignment of the args to parameters is different. def foo(*args) puts args.inspect end def bar(x=1, a:2) puts "x:#{x} a:#{a}" end foo(:a => 1) # [{:a=>1}] foo({:a => 1}) # [{:a=>1}] bar(:a => 1). # x:1 a:1 bar({:a => 1}). # x:{:a => 1} a:2
-
-
github.com github.com
-
“…” would be cool, but (unless I’ve missed something in Ruby 3.2+), it can only delegate all args, and foo(1, …) is impossible.
-
-
github.com github.com
-
The main change with Ruby 3.0 is that it differentiates between passing a hash and passing keyword arguments to a method with variable or optional keyword parameters. So def my_method(**kwargs); end my_method(k: 1) # fine my_method({k: 1}) # crashes
-
my_func(1, 2, 'foo' => 1, :kw => true) # ArgumentError: unknown keyword: "foo" even though Hash.ruby2_keywords_hash?(args.last) returns true.
-
even though Hash.ruby2_keywords_hash?(args.last) returns true. 🤯 And this statement (from #366): # If the last argument is Hash, Ruby will treat only symbol keys as keyword arguments # the rest will be grouped in another Hash and passed as positional argument. doesn't seem to be correct, at least in Ruby 3.0.
-
-
grahamhancock.com grahamhancock.com
-
Dr. Sheehy anecdotally explained his case to Mr. Bonzell, relating how [Howard] Hughes in the early 1960’s claimed the invention of the “ruby laser”, when factually the United States Army at Picatinny Arsenal built the first such device in 1958. The negligence of not seeking a patent for the invention cost the Department of Defense dearly.
On 15DEC17, Dr. James Sheehy, Chief Technology Officer for the Naval Aviation Enterprise, wrote a letter to Phillip J. Bonzell, Primary Patent Examiner of the United States Patent and Trademark Office, requesting immediate action concerning a denied patent application by a certain Dr. Salvatore Cezar Pais, an aerospace engineer at Naval Air Warfare Center Aircraft Division. Dr. Sheehy anecdotally explained his case to Mr. Bonzell, relating how [Howard] Hughes in the early 1960’s claimed the invention of the “ruby laser”, when factually the United States Army at Picatinny Arsenal built the first such device in 1958. The negligence of not seeking a patent for the invention cost the Department of Defense dearly.
The letter concludes with the marginally cloaked implication of United States’ National Security being severely jeopardized by the then current application’s rejection. Dr. Sheehy supported his position stating: ”Based on these initial findings [Dr. Pais’ supporting feasibility experiments] I would assert this will become a reality. China is already investing significantly in this area and I would prefer we hold the patent as opposed to paying forever more to use this revolutionary technology…”
U. S. Patent Application 15/141,270 (PAX205)/B64G1/409 Unconventional spacecraft propulsion systems Patent Number 10,144,532, Granted 4DEC18, Adjusted Expiration 28SEP36
What can we learn from this? 1) The history of the Ruby Laser needs to be rewritten, wikipedia and anything about the laser does not acknowledge what is being claimed here.
2) The Navy has to use an example from 1958/1960 to avoid any issue but still make the point... "just like this other time we didn't patent what we built and therefor it was a mistake... we should patent this new technology... that we haven't made... but in case we did make it like the Ruby Laser, then let's patent it.
-
- Jan 2024
-
andymaleh.blogspot.com andymaleh.blogspot.com
-
www.ruby-forum.com www.ruby-forum.com
-
How to use “case” to match class names? (=== not so funny)
-
One way to potentially get around this is to have an object that simple holds a class and overrides the === operator to make case work properly:
-
-
funnyhow.substack.com funnyhow.substack.com
-
https://funnyhow.substack.com/p/how-chris-rock-and-jerry-seinfeld
Comedian Matt Ruby relates his personal experience watching Chris Rock workshopping his comedy writing in front of auciences at stress Factory in New Brunswick, New Jersey. Rock would show up unannounced and perform new material in front of small crowds to test it out. He'd read/perform material off of a yellow legal pad.
Peter Sims included some of it in the introduction of his book Little Bets.
This is broadly similar to my own experience seeing Rock at the Laugh Factory trying out material for the Academy Awards as well as Adam Sandler at the Improv on Melrose doing midnight sets reading straight off of a notebook.
-
- Dec 2023
-
gitlab.com gitlab.com
-
hashie
-
-
www.pluralsight.com www.pluralsight.com
-
&& nil
first sighting: I don't think I've seen someone write exactly
&& nil
before.Apparently to avoid having the return value from
errors.add
— which should be done solely for its side effect, not to get a return value -- inadvertently being used as a return value foruser
. It wouldn't make sense to return fromuser
. That should only return a User or nil. And more statically typed languages would allow that to be expressed/enforced from type annotations alone, which would have caught the mistake of returningerrors.add
if someone had accidentally attempted to return that.Having
user
(and thereforecall
) return nil is key to theunless @current_user
working.
-
-
opentelemetry.io opentelemetry.io
-
-
Compared with simple clients, modern clients are generally much easier to use and more Ruby-like
-
The libraries in this repo are simple REST clients. These clients connect to HTTP/JSON REST endpoints and are automatically generated from service discovery documents. They support most API functionality, but their class interfaces are sometimes awkward.
-
- Nov 2023
-
-
Autoloading in Rails was based on const_missing up to Rails 5. That callback lacks fundamental information like the nesting or the resolution algorithm being used. Because of that, Rails autoloading was not able to match Ruby's semantics, and that introduced a series of issues. Zeitwerk is based on a different technique and fixed Rails autoloading starting with Rails 6.
-
On reload, the namespaces are safe, won't be reloaded. The loader only reloads what it manages, which in this case is the adapter itself.
-
-
guides.rubyonrails.org guides.rubyonrails.org
-
In this example, we still want app/models/shapes/circle.rb to define Circle, not Shapes::Circle. This may be your personal preference to keep things simple, and also avoids refactors in existing code bases. The collapsing feature of Zeitwerk allows us to do that:
-
-
github.com github.com
-
MessagePack is an efficient binary serialization format. It lets you exchange data among multiple languages like JSON but it's faster and smaller.
Tags
Annotators
URL
-
-
-
Please note that you should also ignore subdirectories that are not meant to be namespaces. For example: Rails.autoloaders.main.ignore('lib/tasks', 'lib/assets') Otherwise, Zeitwerk would define a Tasks constant, but that is not your intention (and could potentially conflict with a genuine Tasks constant).
-
Another alternative that would feel a lot better would be app/my_app in the same way I do lib/my_app, and then app/my_app/my_file.rb would define MyApp::MyFile, like normal. That would be fine, preferable, even. But how do I tell Zeitwerk that?
-
- Oct 2023
-
Tags
Annotators
URL
-
-
codereview.stackexchange.com codereview.stackexchange.com
-
stackoverflow.com stackoverflow.com
-
github.com github.com
-
edgeguides.rubyonrails.org edgeguides.rubyonrails.org
-
options.delete(:expires_in) { ActiveStorage.urls_expire_in }
What is the contents of the block for? When is it invoked?
I assume this is a type, and should have been
fetch() { }
instead?
-
-
stackoverflow.com stackoverflow.com
- Sep 2023
-
bugs.ruby-lang.org bugs.ruby-lang.org
-
One of my favorite aspects of Ruby is how easy it is to write in a functional programming style, and including the scan operation would expand the number of use cases covered by functional methods.
-
I think this is the crux of the issue. Because #inject needs to evaluate every element in order to return a meaningful value, it can't be partially evaluated. The "scan" operation allows for partial evaluation.
-
-
stackoverflow.com stackoverflow.com
-
You just blew my mind Marc-André. My code just went from idiotic to idiomatic.
-
-
rubyreferences.github.io rubyreferences.github.io
-
A new class for containing value objects: it is somewhat similar to Struct (and reuses some of the implementation internally), but is intended to be immutable, and have more modern and cleaner API.
-
Time.new('2023-01-29 00:29:30') # => 2023-01-29 00:29:30 +0200
-
-
-
Tags
Annotators
URL
-
- Aug 2023
-
engineering.universe.com engineering.universe.com
-
edgeguides.rubyonrails.org edgeguides.rubyonrails.org
-
The method name is generated by replacing spaces with underscores. The result does not need to be a valid Ruby identifier though — the name may contain punctuation characters, etc. That's because in Ruby technically any string may be a method name. This may require use of define_method and send calls to function properly, but formally there's little restriction on the name.
-
- Jul 2023
-
stackoverflow.com stackoverflow.com
-
Ruby 2.5+ If your substring is at the beginning of in the end of a string, then Ruby 2.5 has introduced the methods for this: delete_prefix for removing a substring from the beginning of the string delete_suffix for removing a substring from the end of the string
-
-
activerecord-hackery.github.io activerecord-hackery.github.io
-
args: [:parent, :ransacker_args] do |parent, args|
-
-
guides.rubyonrails.org guides.rubyonrails.org
-
Making MoneySerializer reloadable would be confusing, because reloading an edited version would have no effect on that class object stored in Active Job.
-
There, the module object stored in MyDecoration by the time the initializer runs becomes an ancestor of ActionController::Base, and reloading MyDecoration is pointless, it won't affect that ancestor chain.
-
- Jun 2023
-
www.soulcutter.com www.soulcutter.com
-
I’ve heard-suggested that ActiveSupport, which does a ton of monkey-patching of core classes, would make potentially-nice refinements. I don’t hold this opinion strongly, but I disagree with that idea. A big value proposition of ActiveSupport is that it is “omnipresent” and sets a new baseline for ruby behaviors - as such, being global really makes the most sense. I don’t know that anyone would be pleased to sprinkle using ActiveSupport in all their files that use it - they don’t even want to THINK about the fact that they’re using it.
-
Let’s check out what the refinement approach looks like and why I consider it the best way to implement conversion wrappers.
-
under the name “conversion functions.” These exist in Ruby’s standard library - for example Array() is one that you’re likely to see in real code.
-
in the 10 years since they have been a part of Ruby, real life usages are astonishingly rare.
-
- Apr 2023
-
bugs.ruby-lang.org bugs.ruby-lang.org
-
why not allow block forwarding without capturing: foo(&) foo(1, 2, &)
Tags
Annotators
URL
-
-
stackoverflow.com stackoverflow.com
-
You can do an Nth root by raising to a fractional power. For example, the 4th root of 625 is 5. (BigDecimal(625)**(1.0/4.0)).to_f # => 5.0
-
- Mar 2023
-
-
uninclude a module
-
-
stackoverflow.com stackoverflow.com
-
uninclude a module
-
-
-
inline(:C)
inline(:C)
-
-
doorkeeper.gitbook.io doorkeeper.gitbook.io
-
tarasevich.wordpress.com tarasevich.wordpress.com
-
yehudakatz.com yehudakatz.com
-
stackoverflow.com stackoverflow.com
-
When you call 'foo' in Ruby, what you're actually doing is sending a message to its owner: "please call your method 'foo'". You just can't get a direct hold on functions in Ruby in the way you can in Python; they're slippery and elusive. You can only see them as though shadows on a cave wall; you can only reference them through strings/symbols that happen to be their name. Try and think of every method call 'object.foo(args)' you do in Ruby as the equivalent of this in Python: 'object.getattribute('foo')(args)'.
-
def document(f): def wrap(x): print "I am going to square", x f(x) return wrap @document def square(x): print math.pow(x, 2) square(5)
-
- Jan 2023
-
blog.joinmastodon.org blog.joinmastodon.org
-
We need to read the Signature header, split it into its parts (keyId, headers and signature), fetch the public key linked from keyId, create a comparison string from the plaintext headers we got in the same order as was given in the signature header, and then verify that string using the public key and the original signature.
```ruby require 'json' require 'http'
post '/inbox' do signature_header = request.headers['Signature'].split(',').map do |pair| pair.split('=').map do |value| value.gsub(/\A"/, '').gsub(/"\z/, '') # "foo" -> foo end end.to_h
key_id = signature_header['keyId'] headers = signature_header['headers'] signature = Base64.decode64(signature_header['signature'])
actor = JSON.parse(HTTP.get(key_id).to_s) key = OpenSSL::PKey::RSA.new(actor['publicKey']['publicKeyPem'])
comparison_string = headers.split(' ').map do |signed_header_name| if signed_header_name == '(request-target)' '(request-target): post /inbox' else "#{signed_header_name}: #{request.headers[signed_header_name.capitalize]}" end end
if key.verify(OpenSSL::Digest::SHA256.new, signature, comparison_string) request.body.rewind INBOX << request.body.read [200, 'OK'] else [401, 'Request signature could not be verified'] end end ```
-
-
joshfrankel.me joshfrankel.me
-
bundle update rails-controller-testing --conservative. The –conservative flag says when updating this gem do no update any of its dependencies. Using the –conservative flag with bundle is really useful for minimizing changesets as well as avoiding upgrading things that you don’t need to upgrade.
-
-
stackoverflow.com stackoverflow.com
-
class String alias strip_ws strip def strip chr=nil return self.strip_ws if chr.nil? self.gsub /^[#{Regexp.escape(chr)}]*|[#{Regexp.escape(chr)}]*$/, '' end end
-
There is no such method in ruby, but you can easily define it like: def my_strip(string, chars) chars = Regexp.escape(chars) string.gsub(/\A[#{chars}]+|[#{chars}]+\z/, "") end
-
- Dec 2022
-
stackoverflow.com stackoverflow.com
-
Procs can't accept blocks as implicit arguments (the format you're trying). A proc can receive other proc objects as arguments, either explicitly, or using & arguments. Example: a = Proc.new do |&block| block.call end a.call() {puts "hi"}
-
-
www.zhihu.com www.zhihu.com
-
ruby语言有什么样的美学特点?
Tags
Annotators
URL
-
-
github.com github.com
-
has_scope :category do |controller, scope, value| value != 'all' ? scope.by_category(value) : scope end
Tags
Annotators
URL
-
-
github.com github.com
-
Dilemma: Do I use this unofficial library with its really nice idiomatic API or the official library (https://github.com/mailgun/mailgun-ruby) with its inferior API?
I wish this one was still/better maintained because I'd much rather use this API, like:
@mailgun.lists.create "devs@your.mailgun.domain" @mailgun.lists.list @mailgun.lists.find "devs@your.mailgun.domain"
but it's not maintained, and looks like it doesn't have the word
events
in the source at all, so it's missing any way to use the Events API. :(
-
- Nov 2022
-
-
Probaly still prefer: https://github.com/hashie/hashie over this
-
-
github.com github.com
-
Mash duplicates any sub-Hashes that you add to it and wraps them in a Mash. This allows for infinite chaining of nested Hashes within a Mash without modifying the object(s) that are passed into the Mash. When you subclass Mash, the subclass wraps any sub-Hashes in its own class. This preserves any extensions that you mixed into the Mash subclass and allows them to work within the sub-Hashes, in addition to the main containing Mash.
-
foo = Foo.new(bar: 'baz') #=> {:bar=>"baz"} qux = { **foo, quux: 'corge' } #=> {:bar=> "baz", :quux=>"corge"} qux.is_a?(Foo) #=> true
This surprised me.
I would have expected — since Hash literal notation { } was used — that the resulting type would be
Hash
, not the type offoo
. Strange.Is this a good thing... or?
Also, in my quick test, I didn't find this to be true, so...?
``` main > symbol_mash.class => SymbolizedMash
main > { **symbol_mash }.class => Hash ```
-
by using symbols as keys, you will be able to use the implicit conversion of a Mash via the #to_hash method to destructure (or splat) the contents of a Mash out to a block
This doesn't actually seem to be an example of destructure/splat. (When it said "destructure the contents ... out to a block", I was surprised and confused, because splatting is when you splat it into an argument or another hash — never a block.)
An example of destructure/splat would be more like
method_that_takes_kwargs(**symbol_mash)
-
Hashie does not have built-in support for coercing boolean values, since Ruby does not have a built-in boolean type or standard method for coercing to a boolean. You can coerce to booleans using a custom proc.
I use:
ActiveRecord::Type::Boolean.new.cast(value)
-
Mash is an extended Hash that gives simple pseudo-object functionality that can be built from hashes and easily extended. It is intended to give the user easier access to the objects within the Mash through a property-like syntax, while still retaining all Hash functionality.
-
-
-
-
Better option: https://github.com/hashie/hashie
-
-
docs.ruby-lang.org docs.ruby-lang.org
-
A SimpleDelegator instance can take advantage of the fact that SimpleDelegator is a subclass of Delegator to call super to have methods called on the object being delegated to. class SuperArray < SimpleDelegator def [](*args) super + 1 end end SuperArray.new([1])[0] #=> 2
-
-
github.com github.com
-
As simple as Puppeteer, though even simpler.
-
-
www.ruby-forum.com www.ruby-forum.com