text
stringlengths
0
444
* Be sure to https://blog.marc-andre.ca/2010/11/15/methodmissing-politely/[also define `respond_to_missing?`]
* Only catch methods with a well-defined prefix, such as `find_by_*`--make your code as assertive as possible.
* Call `super` at the end of your statement
* Delegate to assertive, non-magical methods:
[source,ruby]
----
# bad
def method_missing(meth, *params, &block)
if /^find_by_(?<prop>.*)/ =~ meth
# ... lots of code to do a find_by
else
super
end
end
# good
def method_missing(meth, *params, &block)
if /^find_by_(?<prop>.*)/ =~ meth
find_by(prop, *params, &block)
else
super
end
end
# best of all, though, would to define_method as each findable attribute is declared
----
=== Prefer `public_send` [[prefer-public-send]]
Prefer `public_send` over `send` so as not to circumvent `private`/`protected` visibility.
[source,ruby]
----
# We have an ActiveModel Organization that includes concern Activatable
module Activatable
extend ActiveSupport::Concern
included do
before_create :create_token
end
private
def reset_token
# some code
end
def create_token
# some code
end
def activate!
# some code
end
end
class Organization < ActiveRecord::Base
include Activatable
end
linux_organization = Organization.find(...)
# BAD - violates privacy
linux_organization.send(:reset_token)
# GOOD - should throw an exception
linux_organization.public_send(:reset_token)
----
=== Prefer `+__send__+` [[prefer-__send__]]
Prefer `+__send__+` over `send`, as `send` may overlap with existing methods.
[source,ruby]
----
require 'socket'
u1 = UDPSocket.new
u1.bind('127.0.0.1', 4913)
u2 = UDPSocket.new
u2.connect('127.0.0.1', 4913)
# Won't send a message to the receiver obj.
# Instead it will send a message via UDP socket.
u2.send :sleep, 0
# Will actually send a message to the receiver obj.
u2.__send__ ...
----
== API Documentation [[api-documentation]]
=== YARD
Use https://yardoc.org/[YARD] and its conventions for API documentation.
=== RD (Block) Comments [[no-block-comments]]
Don't use block comments.
They cannot be preceded by whitespace and are not as easy to spot as regular comments.
[source,ruby]