Tips and Tricks

Episode #455 by Teacher's Avatar David Kimura

Summary

In this episode, we look at various tricks in Ruby on Rails as well as some other neat tricks.
rails tricks 9:47

Chapters

  • Introduction (0:00)
  • Simplified link_to (0:20)
  • present? vs exists? vs any? (1:40)
  • Specific layouts (3:05)
  • HEREDOC (4:58)
  • Opening a gem (7:05)
  • Serve a static site (7:45)
  • Final thoughts (9:30)

Resources

This episode is sponsored by Honeybadger

Summary

Simplified link_to


<%= link_to project %>

# model
def to_s
  name
end

def to_s = name

present? vs exists? vs any?


# Rails Console

Project.find(1).present?
Project.exists?(id: 1)
Project.where(id: 1).any?

Specific layouts


# Terminal
rails g controller admin/welcomes show

# app/views/layouts/admin/welcomes.html.erb
<content>

HEREDOC


# view
<%= some_svg(800, 150) %>

# helper
def some_svg(width=150, height=150)
  <<-HEREDOC.html_safe
    <svg width="#{width}" height="#{height}" xmlns="http://www.w3.org/2000/svg">
      <rect width="#{width}" height="#{height}" x="0" y="0" style="fill:blue;stroke:pink;stroke-width:5;opacity:0.5" />
    </svg>
  HEREDOC
end

Opening a gem


# Terminal
bundle open gem_name

Serve a static site


# Terminal
ruby -run -ehttpd -- --port 3000

code ~/.zshrc
source ~/.zshrc

serve 3000

# ~/.zshrc
serve () {
  ruby -run -ehttpd -- --port $1
}