Wikidata queries

Let’s play with Wikidata (query.wikidata.org)

Return 20 items which are instance of human which have a twitter account:
SELECT ?item ?twitter
WHERE {
?item wdt:P31 wd:Q5 .
?item wdt:P2002 ?twitter .
} LIMIT 20

Screen Shot 2016-06-12 at 11.22.35

Or all Nobel Peace laureates:
Read the rest of this entry »


redirect_back in Rails 5

redirect_back in Rails 5 is handy:

redirect_back(fallback_location: whatever_path)

fallback_location is used when HTTP_REFERER is not present.

In Rails 4 we had to use redirect_to :back and rescue RedirectBackError:

class MyController < ApplicationController
    rescue_from ActionController::RedirectBackError, with: :redirect_to_default

    def action
      redirect_to :back
    end

    private

    def redirect_to_default
      redirect_to root_path
    end
  end

		

My first post in Medium

I wrote a post in Medium about AgreeList.com and why I think it matters. You can also find the code of AgreeList on GitHub.


Rails 5 tutorial: How to create a Chat with Action Cable

David Heinemeier Hansson recorded a screencast building a chat with Action Cable in Rails 5. Here we have a summary:

gem install rails -v 5.0.0.beta1

rails new chat --skip-spring

cd chat

rails g controller rooms show

rails g model message content:text

rails db:migrate

# app/controllers/rooms_controller.rb

class RoomsController < ApplicationController
  def show
    @messages = Message.all
  end
end

# app/views/rooms/show.html.erb

<h1>Chat room</h1>
 
<div id="messages">
  <%= render @messages %>
</div>
 
<form>
  <label>Say something:</label><br>
  <input type="text" data-behavior="room_speaker">
</form>

# app/view/messages/_message.html.erb

mkdir app/views/messages
<div class=“message”>
  <p><%= message.content %></p>
</div>

rails g channel room speak

# app/channels/room_channel.rb

class RoomChannel < ApplicationCable::Channel
  def subscribed
    stream_from "room_channel"
  end

  def unsubscribed
    # Any cleanup needed when channel is unsubscribed
  end

  def speak(data)
    # ActionCable.server.broadcast "room_channel", message: data['message']
    Message.create! content: data['message']
  end
end

In order to turn on action cable on config/routes.rb we add:

mount ActionCable.server => '/cable'

And on app/assets/javascripts/cable.coffee we add:

@App ||= {}
App.cable = ActionCable.createConsumer()

# app/assets/javascripts/channels/room.coffee

App.room = App.cable.subscriptions.create "RoomChannel",
  connected: ->
    # Called when the subscription is ready for use on the server

  disconnected: ->
    # Called when the subscription has been terminated by the server

  received: (data) ->
    $('#messages').append data['message']
    # Called when there's incoming data on the websocket for this channel

  speak: (message) ->
    @perform 'speak', message: message

$(document).on 'keypress', '[data-behavior~=room_speaker]', (event) ->
  if event.keyCode is 13 # return = send
    App.room.speak event.target.value
    event.target.value = ""
    event.preventDefault()

# app/models/message.rb

class Message < ApplicationRecord
  after_create_commit { MessageBroadcastJob.perform_later self }
end

And finally we create app/jobs/message_broadcast_job.rb:

rails g job MessageBroadcast
class MessageBroadcastJob < ApplicationJob
  queue_as :default

  def perform(message)
    ActionCable.server.broadcast 'room_channel', message: render_message(message)
  end

  private
    def render_message(message)
      ApplicationController.renderer.render(partial: 'messages/message', locals: { message: message })
    end
end

The code is on GitHub: https://github.com/HectorPerez/chat-in-rails5

And the video of DHH:


Template Method Pattern

The Template Method Pattern consists of a method that is used as a default value. It is then overwritten in classes that inherit or include it:

class Bicycle
  attr_reader :size, :chain, :tire_size

  def initialize(args={})
    @size = args[:size]
    @chain = args[:chain] || default_chain
    @tire_size = args[:tire_size] || default_tire_size
  end

  def default_chain # <- common default
    '10-speed'
  end
end

This way classes that inherit from Cycle can overwrite default_chain, removing the need of super calls and achieve less coupling:

</pre>
class MountainBike < Bicycle
  def default_chain
    '5-speed'
  end
end

Seen in POODR.


Tools for regular expressions

Some interesting sites:

http://regexr.com

https://regex101.com/r/eB5jY1/1

https://www.debuggex.com/r/mci3WLNmHGTEatf6


Avoid the need for comments

As comments are not executable, they are easily out of date. They are a form of decaying documentation.

If the code inside a method needs a comment, you probably can extract the code into a new method whose name explains what you need to clarify.

Moreover, the Single Responsibility Principle says that classes and methods should have a single responsibility so when you need comments they probably have more than one responsibility.

Therefore instead of:

def gear_inches
  # tire goes around rim twice for diameter
  ratio * rim + (tire * 2)
end

The following is clearer and needs no comment:


def gear_inches
  ratio * diameter
end

def diameter
  rim + (tire * 2)
end

Examples from POODR and here.