Skip to content

Instantly share code, notes, and snippets.

@catm705
Last active August 29, 2015 13:58
Show Gist options
  • Save catm705/10308993 to your computer and use it in GitHub Desktop.
Save catm705/10308993 to your computer and use it in GitHub Desktop.
Rails CODE SNIPPETS: link_to, image_path, form_form, form_tag
<% if flash[:msg] %>
<%= flash[:msg] %>
<% end %>
-------------------------------
<%= link_to "Sign Up", new_user_path(@user) %>
-------------------------------
edit.html.erb (hipchat history)
<%= render 'form' %>
-------------------------------
<%= form_for(@user) do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
<br>
<%= f.label :email %>
<%= f.text_field :email %>
<br>
<%= f.submit "Sign up!" %>
<% end %>
-------------------------------
private
def user_params
params.require(:user).permit(
:email
)
end
-------------------------------
<%= link_to "create picture", new_picture_path(@picture) %>
<br>
<br>
<% @pictures.each do |picture| %>
<img src="<%= picture.image_url %>" alt="" width="300px"/>
<p><strong><%= picture.description %> </strong></p>
<%= link_to "show picture", picture_path(picture) %>
<br>
<%= link_to "edit picture", edit_picture_path(picture)%>
<br>
<%= link_to "Delete", picture_path(picture), method: :delete %>
<br>
<%= link_to "delete picture", { action: :destroy, id: picture.id}, method: :delete %>
<br>
<br>
<% end %>
-------------------------------
show.html.erb (hipchat history)
<img src="<%= @picture.image_url %>" />
<br>
<%= @picture.description %>
<br>
<%= link_to((@picture.image_url), picture_path(@picture)) %>
<%= link_to "edit picture", edit_picture_path(@picture) %>
<%= link_to("delete picture", { action: :destroy, id: @picture.id }, method: :delete) %>
<br>
<h3>Comments: </h3>
<% if @picture.comments %>
<% @picture.comments.each do |comment| %>
<p>Author: <%= comment.author %></p>
<p>Comment: <%= comment.body %></p>
<p>Created at: <%= comment.created_at %></p>
<%= link_to "Delete comment", picture_comment_path(@picture, comment), method: :delete %>
<%= link_to "Delete comment", [comment.picture, comment], method: :delete %>
<% end %>
<% end %>
<%= link_to "Back to Home", pictures_path(@picture) %>
-----------------------------------------------
COMMENTS_CONTROLLER.rb
# POST /pictures/:picture_id/comments(.:format)
class CommentsController < ApplicationController
def create
# This must be :picture_id since it's not a 'user'
@picture = Picture.find(params[:picture_id])
@picture.comments.create(comment_params)
redirect_to picture_path(@picture)
end
def destroy
# KEYS like :id are only based on the route
picture = Picture.find(params[:picture_id])
comment = Comment.find(params[:id])
redirect_to pictures_path
end
private
def comment_params
params.require(:comment).permit(
:author,
:body
)
end
end
-----------------------------------------------
API
user.rb
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# name :string(255)
# email :string(255)
# password_digest :string(255)
# created_at :datetime
# updated_at :datetime
# image_url :string(255)
#
class User < ActiveRecord::Base
has_many :searches
has_many :favorites
has_secure_password
validates(:name, { :presence => true })
validates(:email, { :uniqueness => { case_sensitive: false }})
validates(:password, { :length => { :minimum => 8, :maximum => 16 },
:presence => true,
:confirmation => true }) # must enter confirmation password
INSTAGRAM_ACCESS_TOKEN = ENV['INSTAGRAM_ACCESS_TOKEN']
def self.tag_search(hashtag)
the_data = HTTParty.get("https://api.instagram.com/v1/tags/#{hashtag}/media/recent?access_token=#{INSTAGRAM_ACCESS_TOKEN}")
@my_urls = the_data["data"].map do |image|
image["images"]["low_resolution"]["url"]
end
end
def self.weather_request(city_name)
the_data = HTTParty.get("http://api.worldweatheronline.com/free/v1/weather.ashx?q=#{city_name}&format=json&num_of_days=5&key=52uj5t2aqbycwszq8kmqsa8y")
results = {}
if the_data["data"].include?("error")
flash[:error] = the_data["data"]["error"][0]["msg"]
return false
else
results[:weather_f] = the_data["data"]["current_condition"][0]["temp_F"]
results[:weather_c] = the_data["data"]["current_condition"][0]["temp_C"]
results[:weather_h] = the_data["data"]["current_condition"][0]["humidity"]
results[:weather_desc] = the_data["data"]["current_condition"][0]["weatherDesc"][0]["value"]
results[:weather_icon]=the_data["data"]["current_condition"][0]["weatherIconUrl"][0]["value"]
return results
end
end
end
----------------------------------------------------
pictures_controller.rb
class PicturesController < ApplicationController
# Rails auto creates a new instance of the controller object with every request.
# Controller is really only a ROUTE handler
# Model classes are
def index
@pictures = Picture.all
end
#get '/pictures' => 'pictures#index'
# => ‘ controller#action’
:.
def new
#Need this to populate the form with an instance variable
@picture = Picture.new
end
def edit
@picture = Picture.find(params[:id])
end
def show
@picture = Picture.find(params[:id])
end
def update
@picture = Picture.find_by(id: params[:id])
if @picture.update(picture_params)
flash[:msg] = "Your picture has been updated successfully!"
#This is the 'show' path pictures/:id
redirect_to picture_path(@picture)
else
render :edit
end
end
def create
#@picture.image_url = params[:picture][:image_url]
#@picture.description = params[:picture][:description]
@picture = Picture.new(picture_params)
# OR YOU Can just use 'picture_params' which is a 'strong params'. Much easier!!! and better.
# It's so good b/c you get error messages instead of bugs.
@picture.save
if @picture.save
#default path is to pictures.
redirect_to picture_path(@picture) # "/pictures"
else
render :new
end
end
def destroy
@picture = Picture.find(params[:id])
@picture.destroy
if @picture.destroy
flash[:msg]="Picture was deleted!"
redirect_to pictures_path
else
flash[:msg] = "Couldn't delete picture"
redirect_to pictures_path
end
end
private
def picture_params
params.require(:picture).permit(
:image_url,
:description
)
# it's saying permit the key 'picture' and then the key 'image_url' and 'description'.
# params = { :picture = {:image_url => ?, :description=> ?} }
end
end
------------------------------------------------
___________________________________________________
users_controller.rb
class UsersController < ApplicationController
def index
end
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
redirect_to("/")
else
render :new
end
end
def show
@user = User.find_by(id: current_user.id)
end
def edit
@user = User.find_by(id: current_user.id)
# user.find_by(id: params[:id])
end
def update
@user = User.find_by(id: current_user.id)
if @user.update(user_params)
redirect_to user_path(@user)
else
render :edit
end
end
private
def user_params
params.require(:user).permit(
:name,
:email,
:password,
:password_confirmation,
:image_url
)
end
end
------------------------------------
spec files
user_spec.rb
require 'spec_helper'
describe User do
# Testing relations
# we'll run these specs later.
# prefacing an `it` with `x` changes the tests to pending.
# these one liner tests are from shoulda-matchers.
# I thought we were using expect syntax?! We are! except!
# http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax#comment-564027589
it { should have_many(:searches) }
# validations on our model
it { should validate_presence_of(:name) }
# tests for authentication
it { should have_secure_password }
it { should validate_confirmation_of(:password) }
it { should ensure_length_of(:password).is_at_least(8).is_at_most(16) }
# There's a bug in shoulda-matchers
# https://github.com/thoughtbot/shoulda-matchers/issues/371
it "must have a unique password" do
user = User.create(name: "phil", email: "phil@phil.com", password: "abcd1234", password_confirmation: "abcd1234", image_url: "http://www.davecatweb.com")
expect( user ).to validate_uniqueness_of(:email)
end
end
-----------------------------------------------------
spec/features/new_user_spec.rb --> Using Factory Girl
require 'spec_helper'
describe "the site" do
describe "a new user visits the homepage" do
it "displays a giant rat" do
#browser goes to rat
visit("/")
expect( page ).to have_content "Cappy App"
end
it "displays a giant rat" do
visit root_path
#temporary copy of page
save_and_open_page
expect( page.has_css?('img[alt="giant rat"]') ).to be_true
end
end
it "has a sign-up link" do
visit root_path
click_link "Sign Up"
expect(page).to have_content "Please enter your name"
expect(current_path).to eq "/users/new"
end
describe "creating a user" do
# Given I've entered the correct info
# When I click on sign up
# Then I should go to the homepage
# And I should see "thanks for signing up"
describe "signing up with valid credentials" do
let(:user) {FactoryGirl.build(:user)}
it "takes us to the homepage and says thanks for signing up" do
sign_up(user)
expect(current_path).to eq root_path
expect(page).to have_content "Thanks for signing up!"
end
end
describe "doesn't let you sign up without email" do
let(:user) {FactoryGirl.build(:invalid_user)}
it "doesn't let you sign up" do
sign_up(user)
expect(current_path).to eq new_user_path
expect(page).to have_content "Please enter an email."
end
end
end
end
def sign_up(user)
visit root_path
click_link "Sign Up"
fill_in "Email", with: user.email
click_button "Sign up!"
end
def login(user)
end
-------------------------------------------
Factory Girl
user_factory.rb
FactoryGirl.define do
factory :user do
email "phil@example.com"
end
#need to specify b/c it's not 'user'
factory :invalid_user, class: User do
email nil
end
end
------------------------------------------
spec_helper.rb (To add features - must put in spec_helper)
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
require 'capybara/rails'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment