RubyFlow : The Ruby Community Blog

Home   Submit   Sign Up   Log In   leaders   Twitter   RSS Feed  

croaky — 62 posts

Anonymous functions and closures are a useful concepts included in most modern programming languages. Back to Basics: Anonymous Functions and Closures goes into depth in Ruby and JavaScript on this concept.
Input/Output in Ruby
Input/Output, generally referred to as I/O, is a term that covers the ways that a computer interacts with the world. Screens, keyboards, files, and networks are all forms of I/O. Data from these devices is sent to and from programs as a stream of characters/bytes.

Learn about Ruby's beautiful, duck-typed approach to Input/Output.
“Class-oriented programming” over-emphasizes classes. Class-oriented code can only reference constants, which results in classes which use inheritance instead of composition.

This becomes a problem when you want to mix static state and runtime state, because static state is viral, as static state can only compose other static state.

Avoid passing class names as method parameters as much as possible.
Use RSpec and JSON Schema to create a test-driven process in which changes to the structure of your JSON API drive the implementation of new features.
How can you plug complex, multi-model SQL queries into ActiveRecord models so that you can use them in your views? ActiveRecord Eager Loading with Query Objects and Decorators.
Certain tasks like updating dependencies or migrating a database must be done after pulling code or checking out a branch. Other tasks such as re-indexing our ctags improve our development experience. Both kinds of tasks are easy to forget to do and are therefore error-prone. To address the problem, we’ve recently added a standard, extensible set of git hooks to our dotfiles in order to automate necessary, but annoying tasks.

Never forget again!
Integration tests involving Ruby and JavaScript are fraught with danger. Developers frequently complain of tests which fail erratically. It is possible to write reliable, asynchronous integration tests with Capybara by understanding how Capybara, Ruby, background processes, threads, processes and Capybara drivers such as Selenium, Capybara Webkit, and Poltergeist work, and by following some easy-to-remember guidelines.
Each acceptance test tells a story: a logical progression through a task within an application. As developers, it’s our responsibility to tell each story in a concise manner and to keep the reader engaged, aware of what is happening, and understanding of the purpose of the story.

At the heart of understanding the story being told is a consistent, single level of abstraction; that is, each piece of behavior is roughly similar in terms of functionality extracted and its overall purpose.
Using Clearance with RailsAdmin
Where there is an admin interface, there is also authentication. Most of the documentation out there covers how to integrate RailsAdmin with Devise. But setting up RailsAdmin with Clearance is easy, too!
DNS to CDN to Origin
Content Distribution Networks (CDNs) such as Amazon CloudFront and Fastly have the ability to “pull” content from their origin server during HTTP requests in order to cache them. They can also proxy POST, PUT, PATCH, DELETE, and OPTION HTTP requests, which means they can “front” our web application’s origin like this: DNS -> CDN -> Origin.
Annotating AngularJS inject dependencies got you down? Using Rails? Try disabling variable mangling during JavaScript minification to alleviate your woes.
Last night, I set up an SEO keyword tool and a Twitter+Facebook retargeting tool for seven different websites. Both tools require I add JavaScript snippets to my websites but I didn't touch my codebases or deploy anything new.

I got it done by using, which I've been using for about a year as the primary "Adapter Pattern" for all analytics on my Ruby on Rails apps, Middleman apps, Rack apps, and other static sites. I have Google Analytics and Intercom set up through it and all kinds of other email, customer retention, and analytics tools.

In sum, those tools help me understand whether the things I've built are things that any users or customers actually want, helps me drive traffic to them, and help me grow the products.

Sometimes it's better to interact with from the server-side, though. In and Ruby, Josh talks about how to do it cleanly and in a testable way from inside a Rails app, with RSpec matchers.
When one Ruby method has to know the correct order of another method’s positional arguments, we end up with connascence of position. Ruby 2 Keyword Arguments help us reduce connascence, but there are some edge cases to be aware of.
Don't manually setup your new laptop with a series of copy-and-pasted steps from some blog post. Leverage automation and the open source community to save time and get a more stable result.
Foolproof I18n Setup in Rails
Let’s make I18n on Rails better, quickly and easily. These tips have helped us and caught some easy-to-fix but hard-to-track-down mistakes.
How Rails' Type Casting Works
Have you ever noticed that when you assign a property to an Active Record model and read it back, the value isn’t always the same?

This is because Active Record automatically type casts all input so that it matches the database schema. Depending on the type, this may be incredibly simple, or extremely complex.

Let’s take a look into how the internals work in 4.1.
Developers who are well versed in Ruby on Rails (or other MVC implementations) and start learning Ember.js may find it surprising that, even though there’s shared vocabulary, denoted concepts are sometimes very different.

The first and obvious difference comes from the fact both are web frameworks. Rails facilitates the creation of web apps that offer mainly an HTTP interface to interact with. On the other hand, Ember helps creating web apps that interface directly with humans (through clicks, taps, key presses, etc). They are both web application frameworks, but the former is server side and the latter client side.

A look into their workflows will shed light over the main differences.
SSL certificates can be intimidating but Heroku and DNSimple make the process easy. These steps should take us less than 15 minutes.
Introducing Hound
We're pleased to announce Hound, a hosted service that comments on Ruby style guide violations in your GitHub pull requests.

Hound is currently free and available for public and private GitHub projects. We intend to charge in the near future to ensure Hound is sustainable, but public projects will continue to be free. Hound is also open source.
iOS on Rails is a book for anyone with some Rails experience and little or no iOS experience.

After reading iOS on Rails, you will be able to create a JSON API with Rails and an iOS app that interacts with that API.

The book covers:

* Which tools we chose for rendering JSON endpoints and why
* How to test-drive development of your Rails JSON API
* How to create JSON endpoints for GET, POST, and PATCH requests
* How to create geocoded API endpoints
* How to set up your first iOS app in Xcode
* How to consume and use API endpoints in an iOS app
Polymorphism is one of the fundamental features of object oriented programming, but what exactly does it mean? At its core, in Ruby, it means being able to send the same message to different objects and get different results. Let's look at a few different ways to achieve this in Back to Basics: Polymorphism and Ruby.
Let's say your company's product is a mobile app that gets its data from an internal JSON API. The API, built using Rails, is a few years old. Response objects are large, request latency is high, and your data indicates mobile users aren’t converting because of it. Here's how to evaluate your Rails JSON API for performance improvements.
This article breaks down an HTTP request into its parts, shows how HTTP is leveraged in Rails apps, and how Ajax requests are logged.
This refactoring shows a real-world example of the Builder, Decorator, Chain of Responsibility, and Null Object patterns as well as recursion, using a fold/inject, object composition, and immutable objects in Ruby.
Rendering Collections in Rails
Partials are a great way to break down complex view into more manageable chunks as well as keeping view code DRY. However, rendering a partial for each item in a collection looks ugly. Luckily, Rails gives us this beautiful shorthand syntax:

render @user.comments

How does this magic work? Under the hood, render calls to_partial_path on each of our objects to determine which partial to render.
For several years, there have been two ways of getting in touch with us for feedback regarding our open source projects:

* GitHub, for reporting bugs or submitting patches in the form of pull requests.
* Mailing lists, for general discussion and questions, including ideas for new features.

However, over time, we've grown to feel as though the mailing lists are not pulling their weight.
You won't find polymorphic partials in Rails' API documentation. However, the general programming technique of polymorphism can be applied to Rails partials.
Caching API Requests
When making requests to an external service's API, some requests will frequently occur with the same parameters and return the same result. If we cache our request or response, we can reduce HTTP requests, which can improve performance and avoid hitting rate limits.
Ruby comes with many fantastic Enumerable methods, but the two most useful ones come through Smalltalk via LISP: #map and #inject. What follows are some lengthy method definitions followed by rewrites that are not only more concise but also more clear in their intentions.
Has your app ever encountered a 429 (Too Many Requests) status code when making requests to a third-party API? Getting rate limited can be a nuisance and if not handled properly can result in a negative user experience. While one solution is to catch the exception and ignore it, a better solution is to retry the request.
Don't Stub the System Under Test
The System Under Test helps us focus on what we're really testing, what Depended-On Components (DOC) interact with it, and how to replace a Depended-On Component with a Test Double (such as a stub, spy, or fake).

However, it can be tempting to also stub parts of the System Under Test. This should be avoided.
Rescue StandardError, not Exception
Sometimes our Ruby programs throw errors which we don't have full control over, such as network timeouts. So, we need to catch and handle those errors. To do so, we need to choose an Exception-descended class (or classes) to catch. What's the right granularity of that class?

Rescue StandardError, not Exception.
Using Rack middleware, we can reroute Rack::Test requests to fake remote services without spinning up servers. This example shows how to use that technique to handle the Transparent Redirect HTTP requests for the Braintree payment gateway.
Speed is key. The snappier the site, the more visitors like you. Speed is so important that Google uses it in site rankings and as a major component of its PageSpeed Tools.

Compressing HTTP Responses with Gzip and Rack::Deflater shows how to use Rack::Deflater to drastically reduce the size of your HTML / JSON controller responses.
A Tour of Rails’ jQuery UJS
If you have a look at the default application.js file generated by Rails, you’ll see //= require jquery_ujs. You might know exactly what this require is for, but if you’re like us you know you need it but have only a vague idea of what it’s responsible for.

Maybe you’ve looked at that line and thought, “I should really figure out what that does someday.” Well, for us, today is that day. Please enjoy A Tour of Rails’ jQuery UJS.
The middleware in Rails that parses parameters (ActionDispatch::ParamsParser) runs long before your controller is on the scene, and throws exceptions when invalid JSON is encountered. Fortunately, it's easy to write custom middleware that rescues the errors thrown when JSON can't be parsed.
Requests to external services during test runs can cause several issues:

* Tests failing intermittently due to connectivity issues.
* Dramatically slower test suites.
* Hitting API rate limits on 3rd party sites (e.g. Twitter).
* Service may not exist yet (only documentation for it).
* Service doesn't have a sandbox or staging server.

When integrating with external services we want to make sure our test suite isn’t hitting any 3rd party services. Our tests should run in isolation.

So, here's how to stub external services in tests.
Internationalization (i18n) is the process of adapting computer software to different languages. In Rails, this means extracting all strings from you views and controllers and placing them (by default) into YAML files that live in config/locales. So why would you want to bother with this if your site is only available in English?

The answer is Better Tests Through Internationalization.
Running Specs From Vim
Test driven development thrives on a tight feedback loop. However, switching from the editor to the shell to manually run specs is inefficient.

Tools such as autotest and guard run specs whenever a file gets saved. Although an improvement over a manual workflow, those approaches often run the suite when not needed and run too many or too few specs.

Enter vim-rspec, a lightweight vim plugin that runs specs directly from within vim with the press of a key.
By default, Postgres locks writes (but not reads) to a table while creating an index on it. That can result in unacceptable downtime during a production deploy. On a large table, indexing can take hours.

However, ActiveRecord 4 makes it easy to create Postgres indexes concurrently and avoid accidental downtime caused by long, write-blocking database indexing.
Rails 4 can stream data to the browser with ActionController::Live using server-sent events (SSEs). Mason was curious how server sent events worked so he decided to use them to implement a simple chat application. Tiny-chat is a chat app he built using Goliath, Redis Pub/Sub and of course server-sent events.

Read the source-code walkthrough here.
Rails has built-in support for outgoing mail with ActionMailer, but nothing on the omakase menu resembles handling incoming mail. To help with that, today we’re happy to release Griddler, hot off the… ahem… presses.
./bin/setup convention
A developer should be able to clone the project and run a single, consistent, reliable command to start contributing.
We've seen lots of Rails app test suites that use WebMock to disable HTTP requests. There is also good tools like VCR and techniques like Fakes available for other HTTP requests made from Ruby.

However, modern apps often make HTTP requests to external services from Javascript. We often use services like KISSMetrics, Stripe, Github, LinkedIn, or Facebook from client-side Javascript.

When we use a Capybara driver like Capybara Webkit or Poltergeist, those HTTP requests are no longer stubbed. This post shows how to re-use the Ruby Fakes (written in Sinatra) from the Capybara-with-Javascript-driver acceptance test environment.
Updated an old post to reflect some thoughts on locking gem versions in the Gemfile.
Decorators vs. other patterns
What’s the difference between a decorator and a strategy, composite, and presenter? Giant Robots Smashing Into Other Giant Robots tells all.
There's a single method in your Cucumber suite right now that could silently allow regressions and ambiguity to slip in without you ever knowing. Do you know what it is?
How do you test your gems across multiple versions of its dependencies (like Rails or Capybara)? Try thoughtbot's Appraisal gem.
Factory Girl's new look
Factory Girl release candidates were cut this week. There's a great-looking new syntax and many new conveniences.
Copycopter Client
thoughtbot open sourced copycopter_client a few minutes ago. It's the client library to a corresponding service for editing copy in your live Rails app.
Twiddle Wakka
Do you know the Twiddle Wakka? I thought this was one of the more interesting things I took away from Rubyconf via Jeremy Hinegardner's Anthropology of Ruby talk.
Many people think of Shoulda as a context framework for Ruby tests. It's really two libraries, however. One is a context framework and the other is a set of Rails matchers that only depend on Ruby. This means they can be used in any testing framework (Test::Unit, RSpec, whatever). This post has more details, including how to write your own matchers.
always remember me
Clearance now uses only cookies with a long expiration.
Assuming people using shared computers can't remember to log out is insulting at best and annoying to everyone else that has exclusive access.
Someone recently asked thoughtbot to do “vim on Rails” screencasts. So, we're responding with this experiment. Let us know what you want to see and we'll try to improve things the next time around.
We found a UI edge case that was not as "edge" as we thought: already confirmed users re-clicking their confirmation link. As a result, we altered the underlying library to improve user experience.
Analysis paralysis: access control is an article exploring custom authorization ("access control") in your Rails app using techniques you already know: ActiveRecord associations and finders, current_user. Inherited Resources is also on display to minimize mistakes and keep code standard and clean.
HIGH VOLTAGE is a new Rails engine from thoughtbot for static pages.
Spy vs. Spy - Test Spies
Test Spies make isolation testing easier & maintain the same four-phase test order as unmocked tests.
Open source slides with Slidedown
Have too many slideshows in your organization? Have a jones for open source tools? Text files? Git? Same here. Give Slidedown a whirl.
Registration is open this week for the 2009 Rails Rumble. So start talking ideas and finding teammates at Rumblestiltskin and try to win the Rails Rumble championship belt sponsored by thoughtbot.
Use Shoulda matchers inside RSpec
The latest version of Shoulda works with RSpec. Check out the announcement blog posts for ActiveRecord matchers (last month) and ActionController matchers (today).
Using Umbrella Today? as a case study, thoughtbot will provide Advanced Rails training at Rockefeller Center, NYC on Friday, December 5th. Topics covered include Rails best practice patterns, refactoring with confidence, Test Driven Development with ease, and contributing back to the community with plugins and gems.