Skip to content

Instantly share code, notes, and snippets.

@cdimartino
Created October 1, 2015 15:57
Show Gist options
  • Save cdimartino/0942f08ce49a36946db5 to your computer and use it in GitHub Desktop.
Save cdimartino/0942f08ce49a36946db5 to your computer and use it in GitHub Desktop.
controller.rb
class PostsController < ApplicationController
def index
@published_posts = Post.published
@unpublished_posts = Post.unpublished
end
def create
@post = Post.new params[:post]
if @post.save
redirect_to @post
else
render :new
end
end
end
model.rb
### Use modules ###
#
class User
include Githubable
end
module Githubable
def github_feed
# API call to get the user's github feed
end
def github_profile
# API call to get the user's github profile
end
def github_repos
# API call to get the user's github repos
end
end
### OR with delegation ###
class User
has_one :address
delegate :street, :zip, :number, to: :address, prefix: :shipping
end
class Address
def street
end
def number
end
def zip
end
end
@user.shipping_street -> @user.address.street
@user.shipping_number -> @user.address.number
post.rb
class Post < ActiveRecord::Base
attr_accessor :published_date
before(:save) { self.title.downcase! }
scope :published, -> { where(published: true) }
def self.published
where(published: true)
end
def self.unpublished
where(published: false)
end
def make_legible thing
self.send(thing).gsub('-', ' ')
end
def show_date_for_jenny
self.published_date.strftime("at %I:%M%p for Jenny")
end
end
view.html.erb
<h1><%= post.title %></h1>
<p><%= post.body %></p>
<ul>
<h1>published posts</h1>
<%= @published_posts.each do |post| %>
<li><%= post.title %></li>
<% end %>
</ul>
<ul>
<h1>unpublished posts</h1>
<%= @unpublished_posts.each do |post| %>
<li><%= post.title %></li>
<% end %>
</ul>
view_helper.rb
module ViewHelper
def happy_title str
str.gsub('-', ' ')
end
end
# <% @posts.each do |post| %>
# <%= @post.title.gsub('-', ' ') %>
# <%= happy_title post.title %>
# <% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment