Monthly Archives: August 2018

Hidden features of Ruby you may not know about

Your ads will be inserted here by

Easy Plugin for AdSense.

Please go to the plugin admin page to
Paste your ad code OR
Suppress this ad slot.

Hidden features of Ruby you may not know about

How well do you know the language you’re using? What if I tell you that even you use it the whole day and every day it still can hide some tricks that you might not be aware of? I’d like to reveal some less or more known, but certainly interesting parts of Ruby to make you sure that you don’t miss anything.

Disclaimer

Every example was run with:

→ ruby -v ruby 2.1.2p95 (2014-05-08 revision 45877) [x86_64-darwin13.0] 

and

→ pry -v Pry version 0.10.0 on Ruby 2.1.2 

Binary numbers

[1] pry(main)> 0b110111 => 55  [2] pry(main)> "110111".to_i(2) => 55  [3] pry(main)> "%b" % 55 => "110111"  [4] pry(main)> 55.to_s(2) => "110111" 

Because == 0 is so mainstream

[5] pry(main)> 0 == 0 => true  [6] pry(main)> 0.zero? => true  [7] pry(main)> 0.nonzero? => nil  [8] pry(main)> 1.nonzero? => 1 

nonzero? returns self unless number is zero, nil otherwise.

Get some random date

require 'active_support/core_ext' def random_birth_date_with_age_between_20_and_30   rand(30.years.ago..20.years.ago).to_date end  [9] pry(main)> random_birth_date_with_age_between_20_and_30 => Sun, 21 May 1989 

Call my name

def introduce1   __method__ end  def introduce2   __callee__ end  [10] pry(main)> introduce1 => :introduce1  [11] pry(main)> introduce2 => :introduce2 

Thanks for Thiago A.

Hash from array(s)

[12] pry(main)> ("a".."c").zip(1..3) => [["a", 1], ["b", 2], ["c", 3]] [13] pry(main)> _.to_h => {"a"=>1, "b"=>2, "c"=>3}  [14] pry(main)> colors = ["cyan", "magenta", "yellow", "white"]; [15] pry(main)> Hash[*colors] => {"cyan"=>"magenta", "yellow"=>"white"} 

Note that:

[16] pry(main)> arr.count.even? => true 

In the other case:

[17] pry(main)> Hash[*['one', 'two', 'three']] ArgumentError: odd number of arguments for Hash 

% notation

%q[ ] # Non-interpolated String (except for // /[ and /]) %Q[ ] # Interpolated String (default) %r[ ] # Interpolated Regexp (flags can appear after the closing delimiter) %i[ ] # Non-interpolated Array of symbols, separated by whitespace %I[ ] # Interpolated Array of symbols, separated by whitespace %w[ ] # Non-interpolated Array of words, separated by whitespace %W[ ] # Interpolated Array of words, separated by whitespace %x[ ] # Interpolated shell command 

Of course you can use other non-alpha-numeric character delimiters:

%[including these] %?or these? %~or even these things~  %w what about spaces  %(parentheses) %[square brackets] %{curly brackets} %<pointy brackets> 

Source and examples

‘Better’ errors

class MyCustomBadError < StandardError; end  MyCustomGoodError = Class.new(StandardError) 

Symbol to proc

[18] pry(main)> (1..100).inject(:+) => 5050  [19] pry(main)> ("a".."e").map(&:upcase) => ["A", "B", "C", "D", "E"] 

Enumerators

[20] pry(main)> enum = [1, 2, 3].each => #<Enumerator: ...> [21] pry(main)> enum.next => 1 [22] pry(main)> enum.next => 2 [23] pry(main)> enum.next => 3 [24] pry(main)> enum.next StopIteration: iteration reached an end from (pry):17:in `next' 

however

[25] pry(main)> enum = [1, 2, 3].cycle => #<Enumerator: ...> [26] pry(main)> enum.next => 1 [27] pry(main)> enum.next => 2 [28] pry(main)> enum.next => 3 [29] pry(main)> enum.next => 1 

Let’s be lazy!

[30] pry(main)> range = 1..Float::INFINITY => 1..Infinity [31] pry(main)> range.map { |x| x+x }.first(10) # infinite loop  [32] pry(main)> range.lazy.map { |x| x+x }.first(10) => [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] 

Send a method

Your ads will be inserted here by

Easy Plugin for AdSense.

Please go to the plugin admin page to
Paste your ad code OR
Suppress this ad slot.

Here is nice trick to avoid tedious { |x| do_something_with(x) }. This is a different case from symbol-to-proc, because we don’t invoke method on x but call a method that takes x.

[33] pry(main)> (1..5).each { |x| puts x } 1 2 3 4 5 => 1..5  [34] pry(main)> (1..5).each &method(:puts) 1 2 3 4 5 => 1..5 

Join my array

[35] pry(main)> array = %w(this is an array) => ["this", "is", "an", "array"] [36] pry(main)> array.join ', ' => "this, is, an, array" [37] pry(main)> array * ', ' => "this, is, an, array" 

We have a ternary operator too

def odd?(x)   x % 2 == 0 ? 'NO' : 'YES' end  [38] pry(main)> odd? 3 => "YES" [39] pry(main)> odd? 2 => "NO" 

Rescue to the defaults

[40] pry(main)> value = 1 / 0 rescue 0 => 0 

Interpolate easier

[41] pry(main)> @instance, @@class, $global = [ 'instance', 'class', 'global' ] => ["instance", "class", "global"] [42] pry(main)> p "#@instance, #@@class, #$global"; instance, class, global 

Wrap a method

def caller(block_or_method)   block_or_method.call end  def foo   p 'foo' end  [43] pry(main)> caller lambda { foo } "foo" => "foo" [44] pry(main)> caller -> { foo } "foo" => "foo" [45] pry(main)> caller method(:foo) "foo" => "foo" 

Memoization

fibbonacci = Hash.new do |accumulator, index|   accumulator[index] = fibbonacci[index - 2] + fibbonacci[index - 1] end.update(0 => 0, 1 => 1)  [46] pry(main)> fibbonacci[100] => 354224848179261915075 

Tap here

class Foo   attr_accessor :a, :b, :c end  foo = Foo.new foo.a = 'a' foo.b = 'b' foo.c = 'c'  Foo.new.tap do |foo|   foo.a = 'a'   foo.b = 'b'   foo.c = 'c' end => #<Foo:0x007fe1bd5f6210 @a="a", @b="b", @c="c"> 

Nest some stuff

[47] pry(main)>  nested_hash = Hash.new { |hash, key| hash[key] = Hash.new(&hash.default_proc) } => {} [48] pry(main)> nested_hash[:x][:y][:z] = :xyz => :xyz [49] pry(main)> nested_hash => {:x=>{:y=>{:z=>:xyz}}} 

Daemonize it

# daemon.rb Process.daemon loop do   sleep end 
λ MacBook-Pro-Kamil Desktop → ruby daemon.rb λ MacBook-Pro-Kamil Desktop → ps aux | grep daemon    kamil 41629 0.0 0.0 2472380 472 ?? S 11:45PM 0:00.00 ruby daemon.rb 

Candy shop

require 'yaml/store' store = YAML::Store.new 'candy.yml'  store.transaction do   store['candy']    = "m&m's"   store['lollipop'] = 'Chupa Chups' end  store.transaction do   store.abort # you can resign from buying end  store.transaction do   p store['candy']    # "m&m's"   p store['lollipop'] # 'Chupa Chups' end 

Struct on

Struct.new('Tuple', :first, :second) do   def pair     "(#{first}, #{second})"   end end  [50] pry(main)> struct = Struct::Tuple.new('left', 'right') => #<struct Struct::Tuple first="left", second="right"> [51] pry(main)> struct.pair => "(left, right)" 

Have some defaults

[52] pry(main)> zoo = Hash.new { |hash, key| hash[key] = 0 } => {} [53] pry(main)> zoo.fetch :gorillas, 0 => 0 [54] pry(main)> zoo.fetch :gorillas => 0 [55] pry(main)> zoo[:gorillas] => 0 

And many more.

Painless arrays

# array of size 3 containing only 0s [56] pry(main)> Array.new(3, 0) => [0, 0, 0]  # choose random number and "replicate" it 3 times [57] pry(main)> Array.new(3, rand(10)) => [8, 8, 8]  # build array of size 3 with random number on each index [58] pry(main)> Array.new(3) { rand(100) } => [17, 99, 72] 

Play with URLs

require 'uri'  [59] pry(main)> URI::HTTP.build(['kamil', 'arkency.com', 8080, '/path', 'query', 'fragment']) => #<URI::HTTP:0x007f8efd43a150 URL:http://kamil@arkency.com:8080/path?query#fragment>  require 'active_support/core_ext/object/to_query'  [60] pry(main)>  "http://www.arkency.com?" + { language: "ruby", status: "professional" }.to_query => "http://www.arkency.com?language=ruby&status=professional"  require 'cgi' [61] pry(main)> CGI::parse "language=ruby&status=awesome" => {"language"=>["ruby"], "status"=>["awesome"]} 

Access the hash

require 'active_support/core_ext/hash/indifferent_access'  [62] pry(main)>  rgb = { black: '#000000', white: '#FFFFFF' }.with_indifferent_access => {"black"=>"#000000", "white"=>"#FFFFFF"} [63] pry(main)> rgb[:black] => "#000000" [64] pry(main)> rgb['black'] => "#000000" 

Expand range

[65] pry(main)> p *(1..5) 1 2 3 4 5 => [1, 2, 3, 4, 5]  [66] pry(main)> [*('a'..'e')]  => ["a", "b", "c", "d", "e"]  [67] pry(main)> numbers = *('00'..'10')  => ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10"] 

Less verbose with ;

Did you know that placing a semicolon at the very end of line hides its output? It may be helpful when some expression produces a lot of data, which we want to just assign to variable instead of directly printing in output.

"a"..."z" [68] pry(main)> alphabet = *('a'...'z') [   [ 0] "a",   [ 1] "b",   [ 2] "c",   [ 3] "d",   [ 4] "e",   [ 5] "f",   [ 6] "g",   [ 7] "h",   [ 8] "i",   [ 9] "j",   [10] "k",   [11] "l",   [12] "m",   [13] "n",   [14] "o",   [15] "p",   [16] "q",   [17] "r",   [18] "s",   [19] "t",   [20] "u",   [21] "v",   [22] "w",   [23] "x",   [24] "y" ] [69] pry(main)> alphabet = *('a'...'z'); [70] pry(main)> 

Inspired by 1jgjgjg

Call a proc

In how many ways can we call a proc? Actually in a few:

[71] pry(main)> my_proc = -> argument { puts argument } #<Proc:0x007fb1ebe9c1a0@(pry):7 (lambda)> [72] pry(main)> my_proc.call('hello') hello nil [73] pry(main)> my_proc.('hello') hello nil [74] pry(main)> my_proc['hello'] hello nil 

Thanks for Jordan Running

Summary

Impressed? If no, that’s great! It means you are a trouper. Otherwise, it’s good too, because you learned something new today and I hope you find this useful.

If you have your favourite tricks, you can share them in the comments below.

6 front-end techniques for Rails developers. Part I: From big ball of mud to separated concerns

Your ads will be inserted here by

Easy Plugin for AdSense.

Please go to the plugin admin page to
Paste your ad code OR
Suppress this ad slot.

6 front-end techniques for Rails developers. Part I: From big ball of mud to separated concerns

Photo remix available thanks to the courtesy of Clever Cupcakes. CC BY 2.0

Current trends in web development forces us to write more and more front-end code in our applications. Single Page Applications, content changes without refreshing, rich user experience using custom controls – all those requirements needs you to write code. And this code, as any other code, can quickly turn into a big ball of mud. It can happen when you lack proper tools in your toolbox to design it correctly.

In this course I want to share with you techniques and tools we’re using in our day-to-day work. Some of those allow you to create easier, more testable code. Some of those allow you to develop it faster, without losing quality. I believe it’s really worth to try these techniques and choose which suits you most.

In the part one, I want to present you a simple case of refactoring of a badly written front-end code to a stand-alone micro-app with proper encapsulation.

It’s quite common to see CoffeeScript code which is an imperative chain of DOM transformations and event handlers mixed with AJAX calls. It is a complete disaster when it comes to maintaining and adding new features to it. In addition, all responsibilities in such spaghetti code are entangled. Luckily it’s quite easy to segregate dependencies and create an Application class, which responsibility is to create and configure all objects you’ve separated during refactoring.

Let’s see an example code that you may find in (bad written) front-end codebase. It’s responsible for loading photos data (via an AJAX call) and displaying it on the screen. After clicking on a photo it should be grayed out:

$(document).ready ->   photoHTML = (photo) =>     "<li>        <a id='photo_#{photo.id}' href='#{photo.url}'>          <img src='#{photo.url}' alt='#{photo.alt}' />        </a>     </li>"    $.ajax     url: '/photos'     type: 'GET'     contentType: 'application/json'     onSuccess: (response) =>       for photo in response.photos         node = $(photoHTML(photo)).appendTo($("#photos-list"))          node.on('click', (e) =>           e.preventDefault()           node.find('img').prop('src',              photo.url + '.grayscaled.jpg')         )     onFailure: =>       $("#photo-list").append("<li>                                  Failed to fetch photos.                                </li>") 

Why we should bother?

There are several problems with this code:

  • There is a callback within a callback – and it’s an anti-pattern in JS. It leads to a callback hell – which is unmaintainable in the long term.
  • Initialization is not separated from definition of this code. That means if we don’t want to always run this code we need to create conditionals (like if $("#photos-list").length > 0).
  • SRP is cleanly violated. You have data fetching, DOM manipulation and domain logic (creating grayscaled photo’s URL), event binding – all in one place. There are too many reasons to edit this code at all.
  • Code is not revealing intentions. It’s not a problem now. But think about further features that can be introduced. It can be a real problem when you expand this code to about 50-100 lines.

Fortunately, you can easily refactor this code.

Let’s do this!

As I’ve mentioned before, this code has several responsibilities:

  • Fetching data via an AJAX call
  • Manipulating DOM
  • Knowledge about presenting photo (see line 2 and 18)
  • Logic of creating grayscaled photo URL
  • Binding handlers to DOM events

Your first step should be to create classes with its responsibilities. In our projects it’s quite usual that we have Gui class (often it is composed of a few smaller classes), Backend class (which fetches data from Rails backend and pre-processes them) and UseCase class (which contains business logic within, operating on domain objects). Since this example does not contain much business logic at all, you can stick with only Backend and Gui classes.

Since there is a business rule that is worth to be contained in an intention revealing interface, it’s a good decision to create a Photo domain object.

Start with a domain

When I work in a Sprockets-based stack I usually create a module definition within application.js to make my new classes accessible globally and namespaced. It’s quite simple – you can put Photos = {} in the body of your application.js file. Then you can require your new classes. They’ll be available in a web inspector and in a code in a Photos namespace.

There is a rule of thumb to always start with domain (or use case). In our case it’s a tiny part of code that encapsulates grayscale photo URL transformation logic:

class Photos.Photo   constructor: (@id, @url, @alt) ->    grayscaledURL: =>     @url + ".grayscaled.jpg"    @fromJSON: (json) ->     new Photos.Photo(json.id, json.url, json.alt) 

You can easily transform existing code to accommodate this change. That means you take this as a series of small steps – feel free to stop this refactoring now and jump into next task.

Talking with Rails

Let’s proceed with further decomposition of this code. Right now your can create our Backend class to accommodate AJAX fetching behavior.

I mostly extracted existing implementation here to a method. Here is how I could create such a class:

class Photos.Backend   fetchPhotos: =>     request = $.ajax(       url: '/photos'       type: 'GET'       contentType: 'application/json'     )     .then (response) =>       photos = []       for photo in response.photos         photos.append(Photos.Photo.fromJSON(photo))       photos 

I’ve removed onSuccess and onFailure callbacks here and replaced it with a Promise object. That allows me to expose ‘status’ of AJAX call to anyone interested in a result – exactly what I want if I want to pass control to another object. I’ve also used a neat trick with #then – data for a caller of this method will come encapsulated in your new Photos.Photo object, not raw JSON data.

You can argue that responsibility of backend is not to encapsulate JSON in a domain object. For me Backend is for ‘separating’ world from the heart of your application – which should operate only on a domain objects. In a puristic implementation of a backend, you should create an object which is reponsible for mapping from JSON to domain object – and transform raw JSON data returned by a backend using this object as an intermediate step.

Make it visible

The last step is to create a Gui class, which is responsible for rendering and binding events to the DOM objects. There are different approaches here – in Arkency we’re using Handlebars for templating or React.js for creating the whole Gui part. You can use whatever technology you want – but be careful to not extend responsibilities. The rules of thumb are:

  • When the change hits DOM, it’s Gui (or another objects that Gui is composed of) responsibility to handle DOM manipulation.
  • When an event from UI invokes domain action, Gui should only delegate it to the domain object, not perform it by itself.

There is an example implementation that I’ve written:

class Photos.Gui   constructor: (@dom) ->    photoRow: (photo) =>     $("<li>          <a id='photo_#{photo.id}' href='#{photo.url}'>            <img src='#{photo.url}' alt='#{photo.alt}' />          </a>        </li>")    addPhoto: (photo) =>     photoNode = @photoRow(photo).appendTo(@dom)     @linkClickHandlerToPhoto(photoNode, photo)    linkClickHandlerToPhoto: (photoNode, photo) =>     photoNode.on('click', (e) =>       e.preventDefault()       @switchPhotoToGrayscaled(photoNode, photo)    switchPhotoToGrayscaled: (photoNode, photo) =>     photoNode.find('img').prop('src', photo.grayscaledURL())    fetchPhotosFailed: =>     $("<li>Failed to fetch photos.</li>").appendTo(@dom) 

That’s it. These components contain all the logic we’ve implemented in the previous code. Now we need to coordinate those classes to make a real work.

Putting it all together

Classes that you’ve created cannot do their work alone – they need some kind of coordination between each other. On backend, coordination like that is contained within a service object. If you don’t have service objects, you usually put this responsibility in a controller, which can be done better. That’s why you should create an Application class to initialize and coordinate all newly created objects.

It’s a really simple code. When you perform this refactoring step-by-step, you’ll notice that the end effect of your changes is quite similar to this code. The biggest difference is that you generally want to separate definition of your classes from a real work.

This is what such application object could look like:

class Photos.App   constructor: ->     @gui = new Photos.Gui($("#photos-list"))     @backend = new Photos.Backend()    start: =>     @backend.fetchPhotos()       .done(         (photos) =>           for photo in photos             @gui.addPhoto(photo)       )       .fail(@gui.fetchPhotosFailed) 

This makes the complete, stand-alone app. You’ll notice that you do not run this code yet. That’s because it’s advisable to separate initialization of our app from its definition.

Creating such initializer is easy:

$(document).ready =>   # put logic about starting your app here.   app = new Photos.App()   app.start() 

You can see the end result here.

Summary:

Creating a stand-alone application is a first step to create robust and rich front-end code. Testing it is way easier since responsibilities are segregated and maintainability of this code is increased – when you want to make changes in backend fetching rules you need to focus only on a backend class. It’s only a starting point of course. But it’s a good start for further improvements.

Want more?

This post is a part of the 6-day course about front-end techniques for Rails developers. It’s absolutely free – just register to our newsletter (using a box below) and we’ll teach you 6 techniques we’re using in a day-to-day work, including:

  • Using React.js to ship your Gui faster code and make it easily composable.
  • Techniques we use to prototype front-end without backend to make your clients happier and tighten the feedback loop.
  • Why you should segregating apps by its purpose, not its placement – and how to achieve it in an easy way.
  • Designing your front-end as a many small apps rather than a big one to improve maintainability of your code.
  • Easily make actions on reaction for a domain change, in a dependency-free way using reactive programming with RxJS.

Resources

  • Hexagonal architecture – it is a good way to thinking about creating JS applications at all. Also it comes with a great tooling and even better techniques to improve testability by reducing dependencies (to zero!)
  • Sugar.js – a library which provides us great stdlib extensions to work with domain code within our stand-alone apps. We’re heavily using it in Arkency.
  • YouAreDaBomb – little library which introduces aspect-oriented programming to JavaScript – a great way to provide communication between application objects without specifying dependencies at all. You create a glue class to ‘stitch’ all your adapters and a use case / domain objects together. Neat!

Why we use React.js in our Rails projects

Why we use React.js in our Rails projects

Source: Subramanya Prasad

Programming interactive user interfaces using JavaScript might be a tough task. User calls some action and we need to update his view – manipulating DOM using tool like jQuery. It just doesn’t feel good enough to modify document’s elements by hand. It is also really hard to re-use already written parts of UI and compose them with each other.

Imagine if there was one tool, that would solve all these problems and help you deliver your front-end much faster. What if you didn’t have to worry about this whole DOM stuff when you just want to update the view?

How would you feel being as efficient as when developing your Rails backend, when it comes to user interface?

Here comes React.js!

Our experience with React

Recently in Arkency, we were experimenting with Facebook’s library called React.js. Its only responsibility is to build composable and reactive user interfaces. The power of this tool comes from its simplicity. Learning curve of React is very low, so any new developer comming to project based on React, had no problems with jumping in.

In projects, where we adopted React, we noticed good things happening. The first and the most important, We shipped our front-end significantly faster. We could write really complex UI parts and easily compose with each other. Second, as our apps grew, we improved our code maintainability. Spending less time on maintaining code means more time spent on delivering business value for our customers.

A little bit of theory

React objects are called components. Each of them may contain data and renders view in a declarative way – based only on current data state.

Each React component has 2 inputs:

  • props – shortcut of properties, these are mean to be immutable
  • state – mutable

After changing the state, React will automatically re-render the component to answer a new input.

In addition, all React components must implement render method, which must return another React object or null (from version 0.11).

See it in action!

Assume that we got to create a list of books with a dynamic search.

Why we use React.js in our Rails projects

First, we should create a simple book component that represent single book on a list.

 BooksListItem = React.createClass   render: ->     React.DOM.li({}, @props.book.name) 

To build HTML structure I used built-in React.DOM components, which corresponds to standard HTML elements. In first argument, I pass the empty props object, the second one is just the content of my <li> tag.

Moving on to the full list of Book items

 BooksList = React.createClass   render: ->     React.DOM.ul({className: 'book-list'}, [       for book in @props.books         BooksListItem({book: book})     ]) 

Ok, we are able to display list of books. Now it is high time to implement search. Let’s modify our BooksList component. We need to add form input and handle its changes.

 BooksList = React.createClass   #Component's API method   getInitialState: ->     search: ''    setSearch: (event) ->     @setState search: event.target.value    books: ->     @props.books.filter(       (book) => book.name.indexOf(@state.search) > -1     )    render: ->     # Wrapper that contains another components     React.DOM.div({},       @searchInput()       @booksList()     )    searchInput: ->     React.DOM.input({       name: 'search'       onChange: @setSearch       placeholder: 'Search...'     })    booksList: ->     React.DOM.ul({}, [       for book in @books()         BooksListItem({book: book})       ]) 

Summing it up, you can see the result in a frame below

That’s all you need. After you type something into search input, React will automatically re-render the book list to contain only filtered items.

Getting to an end

Compared to another solutions, you won’t spend much time learning React. You should really give it a shot in your project.

If you look for more information on React, check out official docs and sign-up for our newsletter below. We are going to write more about React.js

4 ways to early return from a rails controller

4 ways to early return from a rails controller

When refactoring rails controllers you can stumble upon one gottcha. It’s hard to easily extract code into methods when it escapes flow from the controller method (usually after redirecting and sometimes after rendering). Here is an example:

1. redirect_to and return (classic)

class Controller   def show     unless @order.awaiting_payment? || @order.failed?       redirect_to edit_order_path(@order) and return     end      if invalid_order?       redirect_to tickets_path(@order) and return     end      # even more code over there ...   end end 

So that was our first classic redirect_to and return way.

Let’s not think for a moment what we are going to do later with this code, whether some of it should landed in models or services. Let’s just tackle the problem of extracting it into a controller method.

2. extracted_method and return

class Controller   def show     verify_order and return     # even more code over there ...   end    private    def verify_order     unless @order.awaiting_payment? || @order.failed?       redirect_to edit_order_path(@order) and return true     end      if invalid_order?       redirect_to tickets_path(@order) and return true     end   end end 

The problem with this technique is that after extracting the code into method you also need to fix all the returns so that they end with return true (instead of just return). If you forget about it you are going to introduce a new bug.

The other thing is that verify_order and return does not feel natural. When this method returns true I would rather expect the order to be positively verified so escaping early from controller action does not seem to make sense here.

So here is the alternative variant of it

2.b extracted_method or return

class Controller   def show     verify_order or return     # even more code over there ...   end    private    def verify_order     unless @order.awaiting_payment? || @order.failed?       redirect_to edit_order_path(@order) and return     end      if invalid_order?       redirect_to tickets_path(@order) and return     end      return true   end end 

Now it sounds better verify_order or return. Either the order is verified or we return early. If you decide to go with this type of refactoring you must remember to add return true at the end of the extracted method. However the good side is that all your redirect_to and return lines can remain unchanged.

Receive free Ruby and Rails tips like this one regularly.
Over 3200 professional Rails devs already subscribed.

3. extracted_method{ return }

class Controller   def show     verify_order{ return }     # even more code over there ...   end    private    def verify_order     unless @order.awaiting_payment? || @order.failed?       redirect_to edit_order_path(@order) and yield     end      if invalid_order?       redirect_to tickets_path(@order) and yield     end   end end 

If we wanna return early from the top level method, why not be explicit about what we try to achieve. You can do that in Ruby if your callback block contains return. That way inner function can call the block and actually escape the outer function.

But when you look at verify_order method in isolation you won’t know that this yield is actually stopping the flow in verify_order as well. Next lines are not reached.

I don’t like when you need to look at outer function to understand the behavior of inner function. That’s completely contrary to what we usually try to achieve in programming by splliting code into methods that can be understood on their own and provide us with less cognitive burden.

4. extracted_method; return if performed?

class Controller   def show     verify_order; return if performed?     # even more code over there ...   end    private    def verify_order     unless @order.awaiting_payment? || @order.failed?       redirect_to edit_order_path(@order) and return     end      if invalid_order?       redirect_to tickets_path(@order) and return     end   end end 

With ActionController::Metal#performed? you can test whether render or redirect already happended. This seems to be a good solution for cases when you extract code into method solely responsible for breaking the flow after render or redirect. I like it because in such case as shown, I don’t need to tweak the extracted method at all. The code can remain as it was and we don’t care about returned values from the subroutine.

throw :halt (sinatra bonus)

In sinatra you could use throw :halt for that purpose (don’t confuse throw (flow-control) with raise (exceptions)).

There was a discussion about having such construction in Rails a few years ago happening automagically for rendering and redirecting but the discussion is inconclusive and looks like it was not implemented in the end in rails.

It might be interesting for you to know that expecting render and redirect to break the flow of the method and exit it immediately is one of the most common mistake experienced by some Rails developers at the beginning of their career.

throw :halt (rails?)

As Avdi wrote and his blogpost Rack is also internally using throw :halt. However I am not sure if using this directly from Rails, deep, deep in your own controller code is approved and tesed. Write me a comment if you ever used it and it works correctly.

why not before filter?

Because in the end you probably want to put this code into service anyway and separate checking pre-conditions from http concerns.

More

Did you like this article? Learn how to make your Rails controllers pretty, refactor to Service Objects and much more from our Fearless Refactorin: Rails controllers

4 ways to early return from a rails controller

Code style matters

Code style matters

Have you ever wondered how your code looks? Exactly – no what it does or even how it is organized, but actually how it looks. One may think here “oh screw it”, but I want to present that it can matter and show you my various thoughts about that topic.

Recently Andrzej Krzywda raised a sensitive issue about code refactoring in Rails Refactoring Book. It provides a brief understanding about existing pains, possible solutions and gives us an opportunity to discuss it more detailed here. This article is intended to be a supplement for that book to show that not only architecture is important.

Why does it matter?

In the beginning I’ll start with some examples in Ruby, that may lead to inconsistency in one project. That’s not a comprehensive example but an overview to introduce this problem.

:key => 'value' vs. key: 'value' 

If you decide to use new ruby (>= 1.9), use also a new hash syntax, or if you are so used to the old one, keep it everywhere in your project, independent of your current mood.

'some string' vs. "some string" 

Why to use double quotes when not interpolating anything?

result = nil if some_condition     result = something else     result = something_else end  vs.  result = if some_condition then something else something_else end  vs.  result = some_condition ? something : something_else 

Here ternary operator is less verbose than if, then, else, end, which are used rather in complex (multiline) cases.

or, and vs. &&, ||  

They can be really tricky so it is not recommended.

['a', 'b', 'c'] and [:a, :b, :c]  vs.  %w(a b c) and %i(a b c) 

Much nicer and no ' everywhere.

I chose these, because I see them the most often. I hope they show that problem exists.

Why I’m pointing on that? Because I’m working in many projects with many devs at one time. I’m using up to 6 different languages every day so sometimes it’s kinda overwhelming. To easily dive into one project from another, switch contexts, jump between environments and work with other people, some guidelines must be respected.

Moreover I’m developing in JetBrains tools (RubyMine, IntelliJ, AppCode, AndroidStudio), which have really nice syntax check inspired by official guidelines like e.g. “Ruby Style Guide” and they help me to keep my code clean and coherent across files.

What is important?

In my opinion, the most important thing about our code is readability. Why? Because we don’t usually have time to read and parse others code. We need to use it. If we are using the same style, we can just take a look and understand everything.

It’s much tougher to understand

unless condition     something else     something_else end 

rather than

if condition     something else     something_else end 

Isn’t it? So the in the first example something will be executed if condition is not true so if it false, yep? Even if parsing takes only a couple milliseconds, when we have a lot of places like that, it may cause wasting more time to refactor code inside our minds.

The other important thing is communication between developers which is done mostly through our code. When we don’t understand what they did and have to reinterpret their code, it means that communication fails. When everyone writes code that have the same look, it’s super-easy to make our work faster. How may times did you have to rewrite a part of code that someone wrote and now you have to implement a new feature? How many times did you complain on others work, because you would do it better?

Where’s the problem?

The main problem is that the taste is sooo subjective. There may be pedants, some that like “artistic mess” or people that don’t care at all. It might be hard to have each of them in one project working on the same code.

Tastes differ. That’s why some writes key: value and some key : value. Some leaves empty lines (one or more) between methods, some don’t do that at all. Some take care of architecture and code separation, but don’t take care of their syntax. Small things, but can be annoying for those that pay attention to such issues.

Of course there are developers which deal with legacy code very well. They easily understand the most tenebrous code, they have huge experience and great skills to interpret any part of existing software. If you are one of them, you may see this blogpost useless, but beware — not everyone is like you. Some learn slower and bad code may discouraged them permanently from the very beginning.

How to solve it?

We cannot have a silver bullet here. Unfortunately code style is really personal and usually hard to change. It’s like old behavior or routine repeated all the time so do not expect immediate switch just like that. So where to begin? A very good start can be guidelines or best practices defined by community or language authors. That may be easy to begin with, learn and improve your code style. There are tons of them for nearly every language. Sometimes even companies define their own guidelines to make it easier and keep concise code across many projects.

How to use them? It might be hard just to remember and use this new code style or guidelines so let’s configure your favorite IDE, find suitable package for Sublime, bundle for TextMate or plugin for VIM that will let you auto-reformat your code. They are usually called YOUR_LANGUAGE-[prettifier | beautifier | formatter] and are available for probably every tool you use to write the code.

Some examples of these guidelines:

Summary

If you think that it’s important topic in your daily work and you are willing to improve your code style I’d recommend you to start from some useful resources guiding you by small steps that will make your code better. Start with small steps, not with everything together. Make a little changes continuously introducing more and more new elements. You’re probably using a few languages at one time so pick one you want to improve and focus on it to avoid too much changes together and decrease new things to remember. Finally, if you want to know our opinion, take the most from Rails Refactoring book.

More useful books that will help you keep your code clean:

  1. Clean code
  2. Clean coder
  3. Beautiful code
  4. The productive programmer
  5. Pragmatic programmer

Code style matters

Developer matters

Developer matters

Have you ever wondered what does your regular workday look like? Do you have the same daily habits? So how is it going? Breakfast, coffee, daily standup, reading mails, some work, off-topic talk with coworkers, dinner, some work and the day is over? If you follow these chain (not necessary in the same order) it is important signal that things must change. Not tomorrow, but right now.

Since I’m working in Arkency, a lot of things changed for me. What is more, recent blogpost by Tomek gave me a fresh overview on my work, being productive and self organized. Moreover, I recently read Robert‘s book Async Remote, which gave me a better understanding of being a good developer so I’d like to share with you my impressions.

What this is about?

Have you ever worked in Agile methodology? You probably have. It is also possible that you were working with Scrum or some kind of its variation depending on your needs. And that is good, because it means you are good. You can deliver, work in dynamic environment, follow iterations and create robust software.

So what next? Why change anything?

This book is intended to show you a different approach to development. A better one? An approach, where developer matters. Not software, neither estimations, nor deadlines. The final book’s appraisal is up to you.

You may wonder right now “why do I need yet another development methodology?”. I am not going to convince you, because that’s not my goal. This book is to give you an opportunity to see how development process can be agile and alternatively to change yours. No pressure, no requirements, just a free talk.

Agile

We are talking about agile, right? But what agile actually is? Agile means transparency.

What’s the most important in dealing with clients, working with teammates, writing a software and managing a project is flexibility. So we have two more buzzwords beyond agile, they are transparency and flexibility and after lecture, you’ll get familiar with concepts behind them, what they truly mean and how to achieve them.

Who should read this book?

It’s good when you can define from the very beginning why do you want to read this book at all. There may be a bunch of reasons so let’s discuss some of them.

Firstly, you might be curious like developers are. It’s good, because you are open-minded, ready to confront with different approach and willing to get to know new solutions. This book is perfect for you then, because it covers all topics, which describes not so standard way to software development and project management.

The another reason is that you want to change something. It’s good too, because it means that you have some expectations. If you expect to find a silver bullet, this book won’t you one. Although it won’t offer you complete and comprehensive solution for all kind of problems, what is written here will definitely open your mind and directs you towards agile way.

To sum up

I recommend you to read a couple of sample chapters on our blog before final decision. After that you can visit book’s website and download a free sample and then click magical blue button, which will change your life forever.

Microservices – 72 resources

Microservices - 72 resources

Microservices – everyone talks about them nowadays. There’s no common understanding however what they are. I’ve been researching this topic for a while, gathering and evaluating articles, presentations and conference videos.

Articles and presentations

Videos

Summary

That’s a lot of reading and watching but not all for sure. I’ll be glad to receive recommendations on publications you find influential.

Service objects as a way of testing Rails apps (without factory_girl)

Service objects as a way of testing Rails apps (without factory_girl)

There’s been recently an interesting discussion about setting up the initial state of your tests. Some are in favor of using built-in Rails fixtures (because of speed and simplicity). Others are in favor of using factory_girl or similar gems. I can’t provide definite numbers but judging based on the apps that we review, in terms of adoption, factory_girl seems to have won.

I would like to present you a third alternative “Setting up tests with services” (the same ones you use in your production code, not ones crafted specifically for tests) and compare it to factory_girl to show where it might be beneficial to go with such approach.

Let’s start with a little background from an imaginary application for teaching languages in schools.

There is a school in our system which decided to use our software and buy a license. Teacher can create classes to teach a language (or use existing one created by someone else). During the procedure multiple pupils can be imported from file or added manually on the webui. The teacher will be teaching a class. The school is having a native language and the class is learning a foreign language. Based on that we provide them with access to school dictionaries suited to kids’ needs.

Everything is ok

Let’s think about our tests for a moment.

let!(:school)     { create(:school, native_language: "en") } let!(:klass)      { create(:klass, school: school) } let!(:pupil)      { create(:pupil, klass: klass) }  let!(:teacher)    { create(:teacher,   school:    school,    languages: %w(fr it), ) }  let!(:dictionary) { create(:dictionary,    native_language:   "en",    learning_language: "fr", ) }  let!(:assignment) { create(:assignment,    klass:      klass,    teacher:    teacher,    dictionary: dictionary, ) }   specify "pupil can learn from class dictionaries" do   expect(     teaching.dictionaries_for(pupil.id)   ).to include(dictionary) end 

So far so good. Few months pass by, we have more tests we setup like that or in a similar way and then we start to stumble upon more of the less common usecases during the conversations with our client. And as it always is with such features, they force use to rethink the underlying architecture of our app.

One of our new requirements is that when teacher is no longer assigned to a class this doesn’t mean that a class is not learning the language anymore. In other words in our domain once pupils are assigned to a class that is learning French it is very unlikely that at some point they stopped learning French (at least in that educational system which domain we are trying to reflect in our code). It might be that the class no longer has a french teacher for a moment (ex. before the school finds replacement for her/him) but that doesn’t mean they no longer learn French.

Because we try to not delete data (soft delete all the way) we could have keep getting this knowledge about dictionaries from Assignments. But since we determined very useful piece of knowledge domain (the fact of learning a language is not directly connected to the fact of having teacher assigned) we decided to be explicit about it on our code. So we added new KlassLanguage class which is created when a class is assigned a new language for the first time.

You don’t even know what hit you

We changed the implementation so it creates KlassLanguage whenever necessary. And we changed #dictionaries_for method to obtain the dictionaries from KlassLanguage instead of Assignment. We migrated old data. We can click through our webapp and see that everything works correctly. But guess what. Our tests fail. Why is that so?

Our tests fail because we must add one more piece of data to them. The KlassLanguage that we introduced.

let!(:klass_language) { create(:klass_language,   klass: klass,    dictionary: dictionary, ) } 

Imagine adding that to dozens or hundred tests that you already wrote. No fun. It would be as if almost all those tests that you wrote discouraged you from refactorings instead of begin there for you so you can feel safely improving your code.

Consider that after introducing our change to code, some tests are not even properly testing what they used to test. Like imagine you had a test like this:

 let!(:assignment) { create(:assignment,   klass:      klass,    teacher:    teacher,    dictionary: french_dictionary ) }  specify "pupil cannot learn from other dictionaries" do   expect(     teaching.dictionaries_for(pupil.id)   ).not_to include(german_dictionary) end 

This test doesn’t even make sense anymore because we no longer look for the dictionaries that are available for a pupil in Assignments but rather in KlassLanguages in our implementation.

When you have hundreds of factory_girl-based test like that they are (imho) preventing you from bigger changes to your app. From making changes to your db structure, from moving the logic around. It’s almost as if every step you wanna make in a different direction was not permitted.

We draw parallel

Before we tackle our problem let’s for a moment talk about basics of TDD and testing. Usually when they try to teach you testing you start with simple data structure such as Stack and you try to implement it using existing language structure and verify its correctness.

 class Stack   Empty = Class.new(StandardError)    def initialize     @collection = []   end    def push(obj)     @collection.push(obj)   end    def pop     @colllection.empty? and raise Empty     @collection.pop   end end 

So you put something on the stack, you take it back and you verify that it is in fact the same thing.

 describe Stack do   subject(:stack) { described_class.new }   specify "last put element is first to pop" do     stack.push(pushed = Object.new)         expect(popped = stack.pop).to eq(pushed)   end end 

Why am I talking about this?

Because I think that what many rails projects started doing with factory_girl is no longer similar to our basic TDD technique.

I cannot but think we started to turn our test more into something like:

 describe Stack do   subject(:stack) { described_class.new }   specify "last put element is first to pop" do     stack.instance_variable_set(:@collection, [pushed = Object.new])     expect(popped = stack.pop).to eq(pushed)   end end 

So instead of interacting with our SUT (System under Test) through set of exposed methods we violate its boundaries and directly set the state. In this example this is visible at first sight because we use instance_variable_set and no one would do such thing in real life. Right?

But the situation with factories is not much different in fact from what we just saw. Instead of building the state through set of interactions that happened to system we tried to build the state directly.

With factories we build the state as we know/imagine it to be at the very moment of writing the test. And we rarely tend to revisit them later with the intent to verify the setup and fix it. Given enough time it might be even hard to imagine what sequence of events in system the original test author imagined leading to a state described in a test.

This means that we are not protected in any way against changes to the internal implementation that happen in the future. Same way you can’t just rename @collection in the stack example because the test is fragile.

In other words, we introduced a third element into Command/Query separation model for our tests. Instead of issuing Commands and testing the result with Queries we issue commands and test what’s in db. And for Queries we set state in db and then we run Queries. But we usually have no way to ensure synchronization of those test. We are not sure that what Commands created is the same for what we test in Queries.

You take revenge

What can we do to mitigate this unfortunate situation? Go back to the basic and setup our tests by directly interacting with the system instead of building its state. In case of our original school example it might look like.

 registration = SchoolRegistration.new registration.call(SchoolRegistration::Input.new.tap do |i|   i.school_attributes  = attributes(:school, native_language: "en")   i.teacher_attributes = teacher_attributes = attributes(:teacher,     id: "f154cc85-0f0d-4c5a-9be1-f71aa217b2c0",      languages: %w(fr it)    ) end)  class_creation = ClassCreation.new class_creation.call(ClassCreation::Input.new.tap do |i|   i.id = "5c7a1aa9-72ca-46b2-bf8c-397d62e7db19"   i.klass_number = "1"   i.klass_letter = "A"   i.klass_pupils = [{     id: "6d805bdd-79ff-4357-88cc-45baf103965a",     first_name: "John",     last_name:  "Doe",   }] end)  assignment = ClassAssignment.new assignment.call(ClassAssignment::Input.new.tap do |i|   i.klass_id   = "5c7a1aa9-72ca-46b2-bf8c-397d62e7db19"   i.teacher_id = teacher_attributes.id   i.learning_language = "fr" end) 

This setup is way longer because in some places we decided to go with longer syntax and set some attribute by hand (although) we didn’t have to. This example mixes two approaches so you can see how you can do things longer-way and shorter-way (by using attributes). We didn’t take a single step to refactor it into shorter expression and to be more reusable in multiple tests because I wanted you to see a full picture of it. But extracting it into smaller test helpers, so that the test setup would be as short and revealing in our factory girl example would be trivial. For now let’s keep focus on our case.

What can we see from this test setup? We can see the interactions that led to the state of the system. There were 3 of them and are similar to how I described the entire story for you. First teacher registered (first teacher creates the school as well and can invite the rest of the teachers). Teacher created a class with pupils (well, one pupil to be exact). Teacher assigned the class to himself/herself as a French teacher.

It’s the last step implementation that we had to change to for our new feature. It had to store KlassLanguage additionally and required our tests to change, which we didn’t want to.

It doesn’t have to be all about DB.

Let’s recall our test:

 specify "pupil can learn from class dictionaries" do   expect(     teaching.dictionaries_for(pupil.id)   ).to include(dictionary) end 

I didn’t tell you what teaching was in our first version of the code. It doesn’t matter much for our discussion or to see the point of our changes but let’s think about it for a moment. It had to be some kind of Repository object implementing #dictionaries_for method. Or a Query object. Something definitely related and coupled to DB because we set the state with factories deep down creating AR objects.

It can be the same in our last example. But it doesn’t have to! All those services can build and store AR objects and communicate with them and teaching would be just a repository object querying the db for dictionaries of class that the pupil is in. And that would be fine.

But teaching could be a submodule of our application that the services are communicating with. Maybe the key Commands/Services in our system communicate with multiple modules such as Teaching, Accounting, Licensing and in this test we are only interested in what happened in one of them. So we could stub other dependencies except for teaching if they were explicitly passed in constructor.

teaching = Teaching.new class_creation = ClassCreation.new(   teaching,    double(:accounting),    double(:licensing) ) 

So with this kind of test setup you are way more flexible and less constrained. Having data in db is no longer your only option.

TL;DR;

In some cases you might wanna consider setting up the state of your system using Services/Commands instead of directly on DB using factory_girl. The benefit will be that it will allow you to more freely change the internal implementation of your system without much hassle for changing your tests.

For me one of the main selling points for having services is the knowledge of what can happen in my app. Maybe there are 10 things that the user can do in my app, maybe 100 or maybe 1000. But I know all of them and I can mix and match them in whatever order I wish to create the setup of situation that I wish to test. It’s hard to set incorrect state that way that would not have happened in your real app, because you are just using your production code.

More

This is an excerpt from Fearless Refactoring: Rails Controllers . For our blog post and newsletter we end up here but in the book there will be a following discussion about shortening the setup. We will also talk about the value of setting UUIDs and generating them on frontend. As well why it is worth to have an Input class that keeps the incoming data for your service (usually user input).

From Rails to RubyMotion: basic toolkit

From Rails to RubyMotion: basic toolkit

Have you noticed the tendency that development is moving strongly towards mobile? There are more and more projects with mobile companion, there are a lot of just-mobile software houses, and there are even only-mobile projects. What if a company has only web developers specialized in Ruby, but want to be really full-stack? Doesn’t matter, with Ruby, it can still goes mobile!

What were the beginnings?

Yet some time ago, if Ruby developer wanted to experiment with Android or iOS, he have to dive into Java or Objective-C. That might have been cumbersome if he only want to play with it, because he had to learn a new language. For these more assiduous it worked – they learned it, used it, then went back do daily work and… forgot it. You know how is that – not used is being forgotten.

Let’s meet RubyMotion

We’d like to introduce here and encourage to use RubyMotion – toolchain that lets you quickly develop native iOS and Android applications using the Ruby programming language.

Our adventure with RM started recently, so we don’t feel skilled enough to present here some advanced code yet. That will happen, for sure, in the next blog posts, so you won’t miss anything. For now we’d like to focus on our research done so far in that area.

As we are RoR developers, we usually depend on gems. They help us not to reinvent the wheel and speed up our development process. Sometimes they are deceptive, but it’s not the topic of this blogpost so let’s say that there are generally helpful. Before we started RM we made some research how does the 3rd party support looks like. What struck us the most is that RubyMotion has tremendous bunch of libraries, pods and gems to improve our productivity. So let’s talk about them.

  1. Libraries – have to be shipped with project, are distributed usually as a compressed packages that require to be extracted and included by developers manually.
  2. Pods – dependencies prepared especially for Objective-C. They were created before RM and are used in many Objective-C projects. Thanks to HipByte, they can be used from Ruby right now.
  3. Gems – they are rubygems prepared for RM and provide nifty solutions for many common problems in native environments.

Frameworks

I’m not sure if framework is the best word word for describing what I want do present now, but in RM world there are some tools that makes mobile platforms completely separate from their native languages end extremely easy to implement. They are essentially gems but this is analogy to Rails among other Ruby gems. Here’s the list:

  • Vanilla RubyMotion – this is RubyMotion itself, that allows to write the same methods taken form native platforms in ruby with just a little tweaks. It’s the closest implementation to Java or Objective-C.

  • ProMotion – it makes verbose Objective-C syntax more ruby-like by hiding native methods behind ruby-convention ones. PM also offers a bunch of ready classes to manipulate views without struggling with sometime complex implementation.

  • RMQ – this is the jQuery for Objective-C. It makes extremely easy to manipleulate views, traverse between components, animate and style whatever we want and handle events and user gestures.

Gether them all

From the many videocasts, sources and examples we’ve extracted basic configurations used among the projects and here they are:

  1. Must-have-one

    • SugarCube – even better syntax for RubyMotion
    • BubbleWrap – a lot of utilities for managing most common platform elements like persistency, global state, notifications and hardware
    • AFMotion – best networking library with beautiful DSL and block callbacks
    • MotionSupport – port of the parts of ActiveSupport that make sense for RubyMotion

  2. Styling (with emphasize on SweetKit)

  3. Models

  4. Frameworks (with preference to simpler for the beginning RMQ)

    • Promotion
    • RMQ (which can use it’s own styling mechanism)

Summary

We encourage every ruby developer to try RubyMotion. It’s a great way to go into mobile even if you don’t know (and like) Java or Objective-C. We are impressed the RubyMotion great support, tools and community despite it’s a standard as befits the Ruby world.

For now, stay tuned for more mobile blogposts!