- Last 7 days
-
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.
-
- Sep 2023
-
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
-
I have been doing different things w/ Ruby for a couple of years now and the only bad thing I can say about it is that it makes programming in other languages feel awfully burdensome. = )
-
-
engineering.appfolio.com engineering.appfolio.com
-
Benoit Daloze of TruffleRuby points out that this is all much easier to read if you define your Ruby internals in Ruby, like they do. He's not wrong.
-
-
www.jvt.me www.jvt.me
-
www.honeybadger.io www.honeybadger.io
-
Until now, we had a lot of code. Although we were using a plugin to help with boilerplate code, ready endpoints, and webpages for sign in/sign up management, a lot of adaptations were necessary. This is when Doorkeeper comes to the rescue. It is not only an OAuth 2 provider for Rails but also a full OAuth 2 suite for Ruby and related frameworks (Sinatra, Devise, MongoDB, support for JWT, and more).
-
The process used to create an OAuth wrapper client is very simple.
-
-
-
gitlab.com gitlab.com
Tags
Annotators
URL
-
-
stackoverflow.com stackoverflow.com
-
github.com github.com
-
def with_something prepare yield on_success end any return, break or throw would skip the on_success code. Skipping over the on_success code also seems quite reasonable when the block calls break and throw. It may not seem like the obvious behaviour for return, but perhaps it is a safe assumption to make in general to think of return as aborting the method yielding to the block. It might be desirable to discourage the use of return in this way for transactions to keep the code clearer, but that would also affect the use of break which seems like a reasonable way to abort a transaction from within the transaction block.
-
-
stackoverflow.com stackoverflow.com
-
If you're nested inside several blocks and can't use next, rather extract the contents of the transaction into its own method and use return there.
-
- Oct 2022
-
stackoverflow.com stackoverflow.com
-
Test.new.test { puts "Hi!" }
-
-
You cannot use yield inside a define_method block. This is because blocks are captured by closures, observe: def hello define_singleton_method(:bye) { yield } end hello { puts "hello!" } bye { puts "bye!" } #=> "hello!"
-
This breaks the TIMTOWTDI rule
-
-
en.wikipedia.org en.wikipedia.org
-
The language was designed with this idea in mind, in that it “doesn't try to tell the programmer how to program.”
-
-
-
Note that one extra type that is accepted by convention is the Boolean type, which represents both the TrueClass and FalseClass types.
-
-
stackoverflow.com stackoverflow.com
-
opts = method(__method__).parameters.map(&:last).map { |p| [p, eval(p.to_s)] }.to_h SomeOtherObject.some_other_method(opts)
-
that's right, we don't want to do params = { ... } because then we're hardcoding the implementation and it becomes very coupled. The benefit of doing it like in my examples is that you can change the method signature and still automatically capture all keyword parameters.
-
Ruby 2.2 introduced Binding#local_variables which can be used instead of Method#parameters
-
-
www.phusionpassenger.com www.phusionpassenger.com
-
blog.appsignal.com blog.appsignal.com
-
def initialize_copy(original_animal) self.age = 0 super end def initialize_dup(original_animal) self.dna = generate_dna self.name = "A new name" super end def initialize_clone(original_animal) self.name = "#{original_animal.name} 2" super end
-
-
github.com github.com
-
But this sounds like spreading fear and doubt when the Ruby parser has no such concepts :) {} always binds tightly to the call right next to it. This block {} will never go to using, unless it's rewritten as do ... end.
-
- Sep 2022
-
bugs.ruby-lang.org bugs.ruby-lang.org
-
@path.yield_self(&File.method(:read)).yield_self(&Parser.method(:new)) ...
-
Tags
Annotators
URL
-
-
github.com github.com
-
Aligning everything with however long the method name is makes every indention different. belongs_to :thing, class_name: 'ThisThing', foreign_key: :this_thing_id has_many :other_things, class_name: 'ThisOtherThing', foreign_key: :this_other_thing_id validates :field, presence: true Compared to the following, which all align nicely on the left. belongs_to :thing, class_name: 'ThisThing', foreign_key: :this_thing_id has_many :other_things, class_name: 'ThisOtherThing', foreign_key: :this_other_thing_id validates :field, presence: true
-
-
github.com github.com
-
I said I wanted begin..end to follow the same indentation principles as if..end because they are semantically related (both are expressions), and I stand by that opinion.
-
-
github.com github.com
-
really begin/end is just a way to pass several expressions where you normally need to pass only one. In this way I think it's much closer to something like conditionals (e.g. if, than to do).
-
-
Tags
Annotators
URL
-
-
rubystyle.guide rubystyle.guide
-
Also be aware of how Ruby handles aliases and inheritance: an alias references the method that was resolved at the time the alias was defined; it is not dispatched dynamically.
-
Prefer alias when aliasing methods in lexical class scope as the resolution of self in this context is also lexical, and it communicates clearly to the user that the indirection of your alias will not be altered at runtime or by any subclass unless made explicit.
reassurance of lack of possibility for run-time shenanigans
Tags
- reassurance
- caveat
- code style
- Ruby: inheritance
- lexical semantics
- inheritance (programming)
- fewer layers of abstraction/indirection
- Ruby
- build time vs. run time
- unambiguous
- lexical semantics vs. run-time semantics
- don't want to be surprised
- no surprises
- good policy/practice/procedure
- alias
Annotators
URL
-
-
-
Ruby's keyword args work a little differently than similar implementations (selectors in Objective C, for instance). The value on the right-hand side of the colon is the default, not the local name.
-
-
stackoverflow.com stackoverflow.com
-
an equivalent of R's signif function in Ruby.
-
-
blog.saeloun.com blog.saeloun.com
- Aug 2022
-
github.com github.com
-
I just learned today that extend apparently doesn't override class methods that are already defined, even though the extend happens later:
-
-
-
auth0.com auth0.com
-
URI::HTTPS.build(host: AUTH0_CONFIG['auth0_domain'], path: '/v2/logout', query: to_query(request_params)).to_s
-
def to_query(hash) hash.map { |k, v| "#{k}=#{CGI.escape(v)}" unless v.nil? }.reject(&:nil?).join('&') end
Tags
Annotators
URL
-
-
github.com github.com
-
Extensions from Ruby are noted in the following list.
Tags
Annotators
URL
-
-
github.com github.com
-
You can pass any options to puma via the server setting Capybara.server = :puma, { queue_requests: true }
-
This very much appears to be a bug or design flaw in puma - The fact that a persistent connection ties up a thread on the chance a request might come over that connection seems like not great behavior. This would really only be an issue when puma is run with no workers (which wouldn't be done in production) but it still seems a little nuts.
-
- Jul 2022
-
avdi.codes avdi.codes
-
stackoverflow.com stackoverflow.com
-
Create a new controller to override the original: app/controllers/active_storage/blobs_controller.rb
Original comment:
I've never seen monkey patching done quite like this.
Usually you can't just "override" a class. You can only reopen it. You can't change its superclass. (If you needed to, you'd have to remove the old constant first.)
Rails has already defined ActiveStorage::BlobsController!
I believe the only reason this works:
class ActiveStorage::BlobsController < ActiveStorage::BaseController
is because it's reopening the existing class. We don't even need to specify the
< Base
class. (We can't change it, in any case.)They do the same thing here: - https://github.com/ackama/rails-template/pull/284/files#diff-2688f6f31a499b82cb87617d6643a0a5277dc14f35f15535fd27ef80a68da520
Correction: I guess this doesn't actually monkey patch it. I guess it really does override the original from activestorage gem and prevent it from getting loaded. How does it do that? I'm guessing it's because activestorage relies on autoloading constants, and when the constant
ActiveStorage::BlobsController
is first encountered/referenced, autoloading looks in paths in a certain order, and finds the version in the app'sapp/controllers/active_storage/blobs_controller.rb
before it ever gets a chance to look in the gem's paths for that same path/file.If instead of using autoloading, it had used
require_relative
(or evenrequire
?? but that might have still found the app-defined version earlier in the load path), then it would have loaded the model from activestorage first, and then (possibly) loaded the model from our app, which (probably) would have reopened it, as I originally commented.
-
-
github.com github.com
-
Compared to https://github.com/aki77/activestorage-validator, I slightly prefer this because - it has more users and has been battle tested more - is more flexible: can specify
exclude
as well asallow
- has more expansive Readme documentation - is mentioned by https://github.com/thoughtbot/paperclip/blob/master/MIGRATING.md#migrating-from-paperclip-to-activestorage - mentions security: whether or not it's needed, at least this makes extra attempt to be secure by using external tool to check content_type; https://github.com/aki77/activestorage-validator/blob/master/lib/activestorage/validator/blob.rb just usesblob.content_type
, which I guess just trusts whatever ActiveStorage gives us (which seems fair too: perhaps this should be kicked up to them to be their concern)In fact, it looks like ActiveStorage does do some kind of mime type checking...
activestorage-6.1.6/app/models/active_storage/blob/identifiable.rb
``` def identify_without_saving unless identified? self.content_type = identify_content_type self.identified = true end enddef identify_content_type Marcel::MimeType.for download_identifiable_chunk, name: filename.to_s, declared_type: content_type end
```
Tags
Annotators
URL
-
- Jun 2022
-
www.theodinproject.com www.theodinproject.com
-
Symbols are an interesting twist on the idea of a string. The full explanation can be a bit long, but here’s the short version:Strings can be changed, so every time a string is used, Ruby has to store it in memory even if an existing string with the same value already exists. Symbols, on the other hand, are stored in memory only once, making them faster in certain situations.One common application where symbols are preferred over strings are the keys in hashes. We’ll cover this in detail in the hashes lesson later in the course.You won’t need to use symbols much in the beginning, but it’s good to get familiar with what they are and what they look like so that you can recognize them.
symbols
Tags
Annotators
URL
-
-
launchschool.com launchschool.com
-
As a documentation convention, methods are listed out with either a :: or a # to indicate two different kinds of publicly accessible methods. Methods denoted by :: are considered class methods, while methods denoted by # are considered instance methods.
In documentation (not actual code):
::
-> class methods#
-> instance methods
Tags
Annotators
URL
-
- May 2022
-
github.com github.com
-
before(:all) do @fiber = Fiber.new do Benchmark.ips do |benchmark| @benchmark = benchmark Fiber.yield benchmark.compare! end end @fiber.resume end
-
does the microgem I published work for your use case?
-
We actually already use this patch: http://myronmars.to/n/dev-blog/2012/03/building-an-around-hook-using-fibers
-
-
disqus.com disqus.com
-
I’ve been looking everywhere for examples of how to use Fibers that are complicated enough to do something useful but simple enough to understand. For an older feature it’s one of the least documented.
-
I haven't done a lot with Fibers,so having you point out a potential use for them and then walk through it was great.
-
-
gist.github.com gist.github.comLICENSE1
Tags
Annotators
URL
-
- Apr 2022
-
stackoverflow.com stackoverflow.com
-
I was wondering particularly whether there is a way to have a comment on the same line as the backslash
-
-
stackoverflow.com stackoverflow.com
-
Caution: + continues the statement but not the string. puts "foo"+"bar".upcase gives you fooBAR, whereas puts ("foo"+"bar").upcase gives you FOOBAR. (Whether or not there's a newline after the +.) But: if you use a backslash instead of the plus sign, it will always give you FOOBAR, because combining lines into one statement, and then combining successive strings into one string, happen before the string method gets called.
-
-
-
It is very important that your gem reopens the modules ActiveJob and ActiveJob::QueueAdapters instead of defining them. Because their proper definition lives in Active Job. Furthermore, if the project reloads, you do not want any of ActiveJob or ActiveJob::QueueAdapters to be reloaded. Bottom line, Zeitwerk should not be managing those namespaces. Active Job owns them and defines them. Your gem needs to reopen them.
-
-
edgeguides.rubyonrails.org edgeguides.rubyonrails.org
-
All known use cases of require_dependency have been eliminated with Zeitwerk. You should grep the project and delete them.
-
-
-
clearcove.ca clearcove.ca
-
export RUBY_THREAD_VM_STACK_SIZE=2000000
This example is how to make stack size larger, but my use case is actually needing to make it smaller.
Why? Because I was debugging a bug that was causing a SystemStackError and it took a long time to hit the stack size limit. In order to iterate more quickly (run my test that exercised the problem code), I wanted to set the stack size smaller, so I did:
export RUBY_THREAD_VM_STACK_SIZE=200
-
-
topdigital.agency topdigital.agency
-
Top Web Design & Development Agencies Winter 2022
Interesting list of agencies. Know guys from ukrainian company Sloboda Studio. They provide high-quality service on time and at a reasonable cost.
-
-
evilmartians.com evilmartians.com
-
I'm a big fan of refinements (yes, I am), and that's what I did to make this code look simpler and more beautiful:
-
- Mar 2022
-
gist.github.com gist.github.com
-
# Allows you to just run "pry" inside a Rails app directory and get # everything loaded as rails c does. Inside a Bundler directory does # what bundle console does.
Tags
Annotators
URL
-
-
rom-rb.org rom-rb.orgROM1
-
mainstream way: ActiveRecord
-
-
rom-rb.org rom-rb.org
-
Ruby Object Mapper (rom-rb) is a fast ruby persistence library with the goal of providing powerful object mapping capabilities without limiting the full power of the underlying datastore.
-
- Feb 2022
-
ruby-doc.org ruby-doc.org
-
There are two pairs of methods for sending/receiving messages: Object#send and ::receive for when the sender knows the receiver (push); Ractor.yield and Ractor#take for when the receiver knows the sender (pull);
-
-
github.com github.com
-
A continuation is like a savepoint, representing "what's left to run" at a given time.
Tags
Annotators
URL
-
-
bugs.ruby-lang.org bugs.ruby-lang.org
-
I am using them in a real life application. I am calculating the available tables for a full calendar with many time slots and with respect to many configurable business rules for restaurants. Using callcc this feature got blazingly fast and very nicely readable. Also we use it to optimise table arrangements with respect to complex restaurant business rules (even something like: Guest A doesn't like to sit near Guest B). Please just have a look at these resources: https://github.com/chikamichi/amb/tree/master/examples http://web.archive.org/web/20151116124853/http://liufengyun.chaos-lab.com/prog/2013/10/23/continuation-in-ruby.html Please help me to keep Guest A away from Guest B. Bad things might happen.
-
-