- Apr 2022
-
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.
-
"Context" manipulation is one of big topic and there are many related terminologies (academic, language/implementation specific, promotion terminologies). In fact, there is confusing. In few minutes I remember the following related words and it is good CS exam to describe each :p Thread (Ruby) Green thread (CS terminology) Native thread (CS terminology) Non-preemptive thread (CS terminology) Preemptive thread (CS terminology) Fiber (Ruby/using resume/yield) Fiber (Ruby/using transfer) Fiber (Win32API) Generator (Python/JavaScript) Generator (Ruby) Continuation (CS terminology/Ruby, Scheme, ...) Partial continuation (CS terminology/ functional lang.) Exception handling (many languages) Coroutine (CS terminology/ALGOL) Semi-coroutine (CS terminology) Process (Unix/Ruby) Process (Erlang/Elixir) setjmp/longjmp (C) makecontext/swapcontext (POSIX) Task (...)
-
-
bugs.ruby-lang.org bugs.ruby-lang.org
-
github.com github.com
-
biggs is a small ruby gem/rails plugin for formatting postal addresses from over 60 countries.
-
- Jan 2022
-
www.ruby-lang.org www.ruby-lang.org
-
Ruby 2.6 introduces an initial implementation of a JIT (Just-In-Time) compiler. The JIT compiler aims to improve the performance of Ruby programs. Unlike traditional JIT compilers which operate in-process, Ruby’s JIT compiler writes out C code to disk and spawns a common C compiler to generate native code. For more details about it, see the MJIT organization by Vladimir Makarov.
-
-
www.destroyallsoftware.com www.destroyallsoftware.comWat1
Tags
Annotators
URL
-
- Dec 2021
-
github.com github.com
-
[ported] to Ruby
Tags
Annotators
URL
-
-
-
How to Create a Micro-Job Marketplace Like Fiverr: Features, Cost, TimelineTimurTech JournalistMarketplaceProduct GuideHomeBlogEntrepreneurshipHow to Create a Micro-Job Marketplace Like Fiverr: Features, Cost, TimelinePublishedNov 19, 2021UpdatedNov 19, 202120 min readIt’s no secret that the COVID-19 pandemic has led many people to reconsider their jobs. Now, freelance as an alternative career path steadily becomes a reality. 50.9% of the U.S. workforce will be freelancing by 2027, a Statista survey shows. Businesses like Fiverr and fellow gig-focused companies rode the wave. To be more precise, they adopted a model allowing the hire of independent contractors without any legwork. How do such tools set the new trend in powering freelancers? In this article, we share proven methods geared towards freelance website growth. Moreover, you will get a glimpse of how to create a micro-job marketplace like Fiverr of your own.
It’s no secret that the COVID-19 pandemic has led many people to reconsider their jobs. Now, freelance as an alternative career path steadily becomes a reality. 50.9% of the U.S. workforce will be freelancing by 2027, a Statista survey shows.
Businesses like Fiverr and fellow gig-focused companies rode the wave. To be more precise, they adopted a model allowing the hire of independent contractors without any legwork. How do such tools set the new trend in powering freelancers?
In this article, we share proven methods geared towards freelance website growth. Moreover, you will get a glimpse of how to create a micro-job marketplace like Fiverr of your own.
Tags
- Fiverr
- How to Create a Micro-Job Marketplace Like Fiverr
- Codcia blog
- custom solution
- cost to build marketplace
- freelance website
- e-markteplace
- marketplace development
- website like Fiverr
- two-sided marketplace
- marketplace website
- Codica
- micro-job website
- custom software
- online marketplace
- Ruby on Rails marketplace
- micro-job marketplace
- micro-job site
- building marketplace
- freelance marketplace
- entrepreneurship
- online marketplace development
- freelance portal
Annotators
URL
-
- Nov 2021
-
-
How to Choose a Reliable SaaS Application Development CompanyKateCloud & SaaS Product ResearcherDmitryCEOSaaSHomeBlogEntrepreneurshipHow to Choose a Reliable SaaS Application Development CompanyPublishedAug 5, 2020UpdatedAug 5, 202012 min readCurrently, SaaS is the largest segment of the global public cloud services market. The growing SaaS industry provides an equal-opportunity atmosphere for businesses. It concerns enterprises from startups to tech giants – and any size in between. It explains why traditional software companies, like Microsoft and Adobe, decided to look into that direction too. Indeed, the time is ripe for developing a SaaS application now. But however tempting it may be, do not dive in headfirst with launching a SaaS product, because sometimes, it can be very challenging. That is why we have prepared a guide on finding a SaaS application development company that will be your best bet.
Looking to build a SaaS app? You will need help of a reliable development team. Check our advice on how to choose a SaaS development company.
Tags
- SaaS MVP
- Ruby gems
- SaaS market
- Ruby on Rails framework
- Ruby
- SaaS development
- RoR developers
- software agency
- software development
- Ruby on Rails
- SaaS hosting provider
- software provider
- software company
- Ruby on Rails development company
- custom software
- Ruby on Rails marketplace
- SaaS
- RoR
- SaaS pricing
- SaaS solutions
- SaaS App
Annotators
URL
-
-
-
SaaS Product Development: Why Choose Ruby on Rails Framework?KateCloud & SaaS Product ResearcherRuby/RailsSaaSHomeBlogTechnologySaaS Product Development: Why Choose Ruby on Rails Framework?PublishedSep 10, 2020UpdatedSep 10, 202013 min readWhich technology to pick for your SaaS business to succeed? This question is not uncommon in our days. In fact, quite the opposite because the SaaS model has become a meaningful part of every business domain. And the demand for SaaS product development is higher than ever and still increasing. This article will discuss the essential factors you need to consider when selecting a framework for your SaaS project. Also, we will introduce the top 3 frameworks for building a SaaS product with their pros and cons. Read on to see the best examples of SaaS applications.
Choosing the right tech stack can help you save costs and make your app stand out in the saturated market. Let’s discuss why Ruby on Rails can be your best choice.
-
-
-
What Makes Ruby on Rails Perfect for Marketplace Development?AlinaE-Commerce & SaaS StrategistMarketplaceRuby/RailsHomeBlogEntrepreneurshipWhat Makes Ruby on Rails Perfect for Marketplace Development?PublishedJul 13, 2020UpdatedJul 13, 202012 min readThe last several years have been marked with the rise of different marketplaces. Airbnb, AliExpress, Etsy, Booking.com are on everyone’s lips. That's not surprising that the idea of launching a second Amazon or eBay seems so appealing. To win the e-commerce race, entrepreneurs focus on providing excellent customer experience and build fast-loading and scalable websites. Besides, business owners take various security measures to protect their customers’ sensitive information. This way, they can gain clients’ trust and boost sales. When building a custom marketplace, what technology stack is best to achieve all these goals? Our answer is simple: Ruby on Rails. In this article, we will fill you in on the Ruby on Rails marketplace development. At Codica, we are passionate fans of this framework and have built numerous e-commerce platforms with its help. Based on our experience, we will discuss the key reasons to choose RoR for building a successful marketplace.
The last several years have been marked with the rise of different marketplaces. Airbnb, AliExpress, Etsy, Booking.com are on everyone’s lips. That's not surprising that the idea of launching a second Amazon or eBay seems so appealing.
To win the e-commerce race, entrepreneurs focus on providing excellent customer experience and build fast-loading and scalable websites. Besides, business owners take various security measures to protect their customers’ sensitive information. This way, they can gain clients’ trust and boost sales.
When building a custom marketplace, what technology stack is best to achieve all these goals? Our answer is simple: Ruby on Rails.
In this article, we will fill you in on the Ruby on Rails marketplace development. At Codica, we are passionate fans of this framework and have built numerous e-commerce platforms with its help. Based on our experience, we will discuss the key reasons to choose RoR for building a successful marketplace.
Tags
- multi-vendor
- Ruby gems
- gems
- emarketplace
- Ruby on Rails framework
- programming languages
- startups
- Ruby
- e-commerce platform
- marketplace development
- RoR developers
- e-commerce
- Ruby on Rails
- ecommerce
- coding
- Ruby on Rails development company
- online marketplace
- Ruby on Rails marketplace
- building marketplace
- RoR
- ecommerce website
- online marketplace development
- framework
Annotators
URL
-
- Oct 2021
-
www.npmjs.com www.npmjs.comsammy1
Tags
Annotators
URL
-
-
-
For those coming from Ruby, Javascript has no builtin method like Ruby’s Array#compact.
-
-
-
Collapsing directories Say some directories in a project exist for organizational purposes only, and you prefer not to have them as namespaces. For example, the actions subdirectory in the next example is not meant to represent a namespace, it is there only to group all actions related to bookings: booking.rb -> Booking booking/actions/create.rb -> Booking::Create
Tags
Annotators
URL
-
- Sep 2021
-
stackoverflow.com stackoverflow.com
-
Thanks to Rack Middleware and Rails 3 you can output pretty JSON for every request without changing any controller of your app. I have written such middleware snippet and I get nicely printed JSON in browser and curl output.
-
-
stackoverflow.com stackoverflow.com
-
The important thing to understand is that there is no such thing as a class method in Ruby. A class method is really just a singleton method. There is nothing special about class methods. Every object can have singleton methods. We just call them "class methods" when the object is a Class because "singleton method of an instance of Class" is too long and unwieldy.
-
Class methods are actually instance methods defined on the singleton class of a class.
-
- Aug 2021
-
gist.github.com gist.github.com
-
medium.com medium.com
-
What if I told you there was a way to do this in Ruby?:destructure def adds(a: 1, b: 2) a + bendadds(a: 1, b: 2)# => 3adds(OpenStruct.new(a: 1, b: 2))# => 3Foo = Struct.new(:a, :b)adds(Foo.new(1,2))# => 3
-
def destructure(method_name) meta_klass = class << self; self end method_proc = method(method_name) unless method_proc.parameters.all? { |t, _| t == :key } raise "Only works with keyword arguments" end arguments = method_proc.parameters.map(&:last) destructure_proc = -> object { values = if object.is_a?(Hash) object else arguments.map { |a| [a, object.public_send(a)] }.to_h end method_proc.call(values) } meta_klass.send(:define_method, method_name, destructure_proc) method_nameend
-
-
www.martinfowler.com www.martinfowler.com
-
this kind of run-time code generation is certainly more natural in Ruby, it's one of its Lispish elements
-
Rubyists don't call these things annotations. One of the things I like doing is to find common techniques that cross languages, for me this is a common technique and 'annotation' seems like a good generic word for it. I don't know if Rubyists will agree.
-
-
www.martinfowler.com www.martinfowler.com
-
An internal DSL (often called an Embedded DSL) is a DomainSpecificLanguage that is written inside an existing host language. It's a common way of thinking in a number of programming language communities - particularly the Lisp community. It's now gaining a lot of attention as DSLs are a common way of thinking in the rapidly growing Ruby community.
Tags
Annotators
URL
-
-
-
# And standalone like a case:Qo.match(people.first, Qo.m(age: 10..19) { |person| "#{person.name} is a teen that's #{person.age} years old" }, Qo.m(:*) { |person| "#{person.name} is #{person.age} years old" })
-
# How about some "right-hand assignment" pattern matchingname_longer_than_three = -> person { person.name.size > 3 }people_with_truncated_names = people.map(&Qo.match_fn( Qo.m(name_longer_than_three) { |person| Person.new(person.name[0..2], person.age) }, Qo.m(:*) # Identity function, catch-all))
-
-
-
Provides empty Module#ruby2_keywords method, for the forward source-level compatibility against ruby2.7 and ruby3.
-
-
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
- new feature
- good explanation
- backwards compatible
- good/preferred/recommended behavior
- ruby: keyword arguments
- Ruby 3
- edge cases
- ruby: ArgumentError
- unfortunate
- good example
- Ruby
- incompatible
- not:
- package/tool to help with transition
- newer/better ways of doing things
- argument delegation
- being explicit
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
- metaprogramming
- encapsulation
- Ruby
- programming languages: external objects have direct access to instance variables
- Ruby: instance variables
- languages: differences
- brevity
- programming: access modifiers (public/private)
- JavaScript: private instance accessors
- convention
- best practices
- JavaScript
- accessors
- I agree
- concise
- balance
- idiomatic Ruby
- safety (programming)
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
- recommended software
- where it shines / best application
- one-liners
- clever
- recommended library
- analogy
- gem: facets
- Ruby: to_proc
- Ruby
- not:
- I have a differing opinion
- ruby library
- clever solution
- reduce
- my comments
- I disagree
- distinction
- appropriateness
- I agree
- example of: reduce
- concise
- generalizable
- Ruby: instance_eval
- idiomatic (programming)
- easy to falsely assume
- too clever
- appropriate use case
- ruby: arrays
- idiomatic Ruby
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
- expected library/language to have feature but is missing
- interesting approach/solution
- simple solution
- I agree
- ruby: core extensions: hash
- solving/handling the general case
- objects/hashes
- Ruby
- solving/handling specific case instead of the general case because general solution would be too hard/complex
- can't support everything / all cases
- Ruby: core
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
- backwards compatible
- constant evolution/improvement of software/practices/solutions
- operators
- resurgence
- ruby
- ruby: hash object destructuring
- JavaScript
- improvement
- feature parity
- good example
- equivalent/analogous/alternative ways to do something between 2 libraries/languages/etc.
- object destructuring
- scope (programming)
- funny
- error/exception handling
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
- recommended software
- too complicated
- active_interaction
- switching/migrating to something different
- missed opportunity
- I agree
- ruby
- concise
- flexibility
- pointing out gaps/downsides/cons in competition/alternatives
- evaluating software options
- recommended option/alternative
- hard to understand
- reform (Ruby)
- too coupled/dependent
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