background preloader

Ruby

Facebook Twitter

Seven Reasons I Love Minitest. The other day at our company standup, I mentioned that I was eager to read an article on Concurrency in Minitest that was featured in Ruby Weekly.

Seven Reasons I Love Minitest

One of my coworkers asked: “people still use Minitest?” My reply: “you mean you’re not using Minitest yet?” I love Minitest. It’s small, lightweight, and ships with Ruby. It’s used by respected programmers like Aaron Patterson, Katrina Owen, Sandi Metz, and of course, DHH. Witness the Firepower of this Fully Armed and Operational Testing Tool. 4 Fantastic Ways to Set Up State in Minitest. When it comes to exercising a piece of application logic with automated unit tests, there’s a well-understood process that most frameworks and testing tools follow: Setup: Establishes instances of data objects and preconditions essential for running the test.Exercise: Executes the method or logic to be tested.Verify: Verifies that the tested method has produced the expected result by making one or more assertions.Teardown: Cleans up or resets application state that should not be allowed to persist between tests.

Perform a Google search for “unit test anatomy”, and you’ll see this same pattern described in books and articles for many programming languages and methodologies - sometimes with slightly different terminology, but still following the same basic sequence. Delegating All of the Things With Ruby Forwardable - Words and Code. It was the best of times.

Delegating All of the Things With Ruby Forwardable - Words and Code

It was the worst of times. It was…refactoring time! Well it was for me yesterday, at least. Refactoring your own code has a great payoff at the end, but boy, does it take some work to get there. A Pattern For Using Standard In And Out In Your Ruby Code - Josh Nichols on the Internet. If you think about it, programming is really about taking some input from a user, and displaying some output back to them.

A Pattern For Using Standard In And Out In Your Ruby Code - Josh Nichols on the Internet

When we’re down at the command line, this usually means reading from the standard input and writing to the standard output. In ruby, you’ll see code that interacts with standard in and standard out like so: class MyApp def prompt_user user_selection = gets.chomp # => 'ponies' puts "User selected: #{user_selection}" # Displays User selected: ponies user_selection endend Sadly though, when it comes testing, usually the input/output stuff is glossed over.

Why though? Extraneous output is often generated during testing It’s hard to specify what stdin returns and verify what stdout displays back to the user. DockYard Blog - Design Patterns Articles. Design Patterns: The Command Pattern By: Doug Yun Exploring design patterns and their use cases.

DockYard Blog - Design Patterns Articles

When Is a Ruby Set Better Than a Ruby Array? Using a Set in Ruby Ruby’s Set supports all of the common set operations including union, intersection, and subtraction.

When Is a Ruby Set Better Than a Ruby Array?

It includes methods to check if a Set is a subset or superset of another Set (or the proper versions of either of those relationships). It also provides a powerful divide method which allows you to partition the Set into subsets based on a given block. As you might suspect, the Set class also implements the enumerable module. This gives you access to the common iterators and gives greater interoperability between Sets and Arrays, as many of the operations that don’t make sense in the context of a set (such as sort) will return an array with the expected results.

Set or Array? Ruby Operators. The Truth about BDD - Clean Coder. I really like the concept of BDD (Behavior Driven Development).

The Truth about BDD - Clean Coder

I think Dan North is brilliant, and had done us all a great service by presenting the concept. Best tips and practices from Ruby experts. As you work with Ruby a lot and develop applications, you will start using more and more components, like fast RESTful APIs or any other frameworks.

Best tips and practices from Ruby experts

In that situation you need to think about separating responsibilities and business logic. For example, if you are using Ruby on Rails, you should start using ActiveRecord and keep all rake tasks outside the Rails. Let’s now imagine you want to create a new restful API using Grape, but you don’t want to end up replicating models. What can you do? One way to do this is to move your models and core tasks to a Gem so it can be decoupled and used anywhere. Ruby reflection. If you are here, then most probably you want to know more about ruby reflection interface.

Ruby reflection

Well that’s true, but I always find myself in need to explain few things before I get started with my posts, and this time I find myself in need of explaining few things related to ruby’s OOP. I’m pretty sure that you always heard that “in ruby: everything is an object.” , but have you ever thought of that carefully? Ruby map, each, collect, inject, reject, select quick reference. Map Performs an action on each array element.

Ruby map, each, collect, inject, reject, select quick reference

The original array is not modified. Returns the modified array. [1,2,3,4,5,6,7,8,9,10].map{|e| e*3 } 3 killer features that are coming in Ruby 2.0. Ruby 2.0 will be released on 2/24/2013, exactly 20 years after development on it began.

3 killer features that are coming in Ruby 2.0

Akira Matsuda during his excellent talk at Rubyconf, brought to my attention 3 very interesting features that will make it more elegant than it already is, specially for Ruby on Rails applications. Refinements Refinements are, for a lack of a better explanation, scoped monkey patches. Let's say that, for some imaginary reason, you want to make any String append a series of periods to all of its instances when calling to_s. One way to do it, would be to monkey patch the String class, and just append the desired text by overriding its to_s method: 3 killer features that are coming in Ruby 2.0. Ruby Programming Language.

Create recursive OpenStruct from a Ruby Hash - Andrea Pavoni. When I develop some ruby app, mostly rails ones, I need to manage several configuration variables (eg: API keys) and I like to store them in a unique place. So I usually end up with something like this: # config/initializers/_load_config.rb path = File.read("#{Rails.root}/config/config.yml") APP_CONF = ActiveSupport::HashWithIndifferentAccess.new( YAML.load(ERB.new(path).result)[Rails.env]) It does a good job: it first compiles eventual ERB tags (so you can store values in ENV) then it loads YAML finally initializes a HashWithIndifferentAccess, so I can lookup keys with either a String or a Symbol The last point is a plus, kindly offered by Rails’ ActiveSupport library, I prefer Symbol over String for Hash keys.

The problem However, I knew that there’s a smarter way to achieve same goal, even with some more adavantages. It solves the problem of Hash key lookup by providing them as methods, for example: Json. Keep it simple, stupid Generate json from ruby struct.

Design_patterns

Ruby reflection. Threading. Mwoods79/bubot. List comprehension in Ruby. RubyDoc.info: Documenting RubyGems, Stdlib, and GitHub Projects. Leveraging Test Data Builders in Cucumber Steps. Finding the balance between writing declarative scenarios and step reuse in Cucumber can be tricky at times. I have found leveraging a Test Data Builder library (often selling itself as an Object Mother library) helps in step reuse and prevents your scenarios from being overloaded with a lot of noise. There are many test data builder libraries out there to do this.

Some of the popular ones are: Fixjour, FixtureReplacement, and FactoryGirl. (There are tons more on github.) In the context of Cucumber these test builders work well when you need to create some records with default values in Given steps. . # support/string.rb# Examples:# "'Foo', 'Bar', and 'Jar'".extract_list # => ["Foo", "Bar", "Jar"]# '"Dog", "Cat"'.extract_list # => ["Dog", "Cat"]class String def extract_list self.scan((/['"](.*?) Module.prepend: a super story - The Hashrocket Blog. I was super excited when I first heard about the prepend feature included in the Ruby 2.0 release, but never had a chance to use it. Micah Cooper and I were working in an existing code base recently, and one of the project's requirements was to log API requests that took longer than a given threshold. The project talked to multiple APIs via XML, JSON and SOAP.

We didn't want to change the existing code, because it had been tested and was working in production. Our approach was to make the smallest change possible to the code base, so we came up with a simple DSL that would wrap the current methods without making any modifications. Ruby: inject. I love inject. To be more specific, I love Enumerable#inject. I find it easy to read and easy to use. It's powerful and it lets me be more concise. Enumerable#inject is a good thing. Of course, I didn't always love it. Ruby Threads: Ruby Study Notes - Best Ruby Guide, Ruby Tutorial. Ruby Threads: Ruby Study Notes - Best Ruby Guide, Ruby Tutorial. Design Patterns: The Observer Pattern. Delightful lessons for dedicated programmers - Practicing Ruby. Best tips and practices from Ruby experts. Metaprogramming in Ruby: Part 2. Ryan Angilly — Dynamically adding class methods in Ruby. Technical notes, my online memory: Ruby Time and DateTime: parse a string, compute the difference, simple right?

Design Patterns: The Observer Pattern. Acceptance Test Frameworks. Exception and Error Handling. Demonstrating exceptions Before the formal description of the the begin/rescue block, let's walk through a couple examples of it in action. At a skin-deep level, it behaves nearly the same as the if/else construct. Skipping past an error.

Cucumber

Hash. Hsh == other_hash → true or false click to toggle source Equality—Two hashes are equal if they each contain the same number of keys and if each key-value pair is equal to (according to Object#==) the corresponding elements in the other hash. Schools. GEM.