rails 小代码合集 view controller model

Rails Create an image with link using the image helper
<%= link_to image_tag("rails.png", alt: "Rails"), 'http://rubyonrails.org' %>01.gemfile


#long_block_rhs.rb
def self.logger
@logger ||= begin
(defined?(Rails) && Rails.logger) ||
(defined?(RAILS_DEFAULT_LOGGER) && RAILS_DEFAULT_LOGGER) ||
default_logger
end
end

#simpler_rhs.rb
def self.logger
@logger ||= (rails_logger || default_logger)
end

def self.rails_logger
(defined?(Rails) && Rails.logger) || (defined?(RAILS_DEFAULT_LOGGER) && RAILS_DEFAULT_LOGGER)
end


Adding additional folders to autoload in your Rails app (Rails 4) 
development.rb
config.autoload_paths += [
"#{Rails.root}/app/contexts",
"#{Rails.root}/app/observers",
"#{Rails.root}/app/application",
"#{Rails.root}/app/workers",
]



<%= debug(session) if Rails.env.development? %>
<%= debug(params) if Rails.env.development? %>
Rails.application.config.paths["log"].first
Rails.env.staging?
config = YAML.load(File.read(Rails.root.join("config","config.yml")))[Rails.env].symbolize_keys
Rails.env => "development"

Rails.cache.write('test-counter', 1)
Rails.cache.read('test-counter')

Rails.application.config.database_configuration[Rails.env]["database"]# Rails: current database name

Rails.logger.info "Hello, world!" #initializer.rb#可以借此观察 加载顺序

<%= Rails::VERSION::STRING %> #Rails: Rails version



initializer.rb
ActiveSupport::Notifications.subscribe "sql.active_record" do |name, start, finish, id, payload|
Rails.logger.debug "=============================================="
Rails.logger.debug "SQL: #{payload[:sql]}"
Rails.logger.debug "=============================================="
Rails.logger.debug caller.join("\n")
Rails.logger.debug "=============================================="
end


Clear Rails cache store and do it fast (without loading the whole Rails environment)

cache.rake
# bundle exec rake cache:clear
namespace :cache do
desc "Clear Rails.cache"
task :clear do
Object.const_set "RAILS_CACHE", ActiveSupport::Cache.lookup_store(Rails.configuration.cache_store)
Rails.cache.clear
puts "Successfully cleared Rails.cache!"
end
end


Use Guard to restart Rails development server when important things change
guard-rails.rb
def rails
system %{sh -c '[[ -f tmp/pids/development.pid ]] && kill $(cat tmp/pids/development.pid)'}
system %{rails s -d}
end

guard 'shell' do
watch(%r{config/(.*)}) { rails }
watch(%r{lib/(.*)}) { rails }
end
rails


devise
https://gist.github.com/oma/1698995
_admin_menu.html.erb
<!--
Used for https://github.com/rubykurs/bootstrap
branch auth


gem 'devise'
$ rails g devise:install
$ rails g devise admin
$ rake db:migrate

<% if admin_signed_in? %>
<li><%= link_to "Sign out", destroy_admin_session_path, :method => :delete %> </li>
<% else %>
<li><%= link_to "Admin", new_admin_session_path %></li>
<% end %>



access Helper Methods in Controller
# Rails 3
def index
@currency = view_context.number_to_currency(500)
end

# Rails 2
def index
@currency = @template.number_to_currency(500)
end



drop table rails
rails c
ActiveRecord::Migration.drop_table(:users)


# This command will list all table in a rails app in rails console
ActiveRecord::Base.connection.tables

app/models/user.rb
class User < ActiveRecord::Base
establish_connection(
YAML.load_file("#{Rails.root}/config/sessions_database.yml")[Rails.env]
)
end





$ rails c
> @kitten = Kitten.first
> Rails.cache.write("kitten_#{@kitten.id}", @kitten)
=> "OK"
> Rails.cache.read("kitten_1")
=> #<Kitten id: 1, cute: "no">
> exit

$ rails c
> Rails.cache.read("kitten_1")
=> ArgumentError: undefined class/module Kitten
> Kitten
=> Kitten(id: integer, cute: string)
> Rails.cache.read("kitten_1")
=> #<Kitten id: 1, cute: "no">



Example of rails console SQL dumping and result formatting
development.rb
# dump SQL into console
require 'logger'
if ENV.include?('RAILS_ENV') && !Object.const_defined?('RAILS_DEFAULT_LOGGER') # rails 2
Object.const_set('RAILS_DEFAULT_LOGGER', Logger.new(STDOUT))
else # rails 3
ActiveRecord::Base.logger = Logger.new(STDOUT) if defined? Rails::Console
end

# enable result formatting - install gem 'hirb'
require 'hirb'
Hirb.enable


A spec demonstrating how stub_env works
it "passes" do
stub_env "development" do
Rails.env.should be_development
end
Rails.env.should be_test
end



Run rake task from capistrano

deploy.rb
desc 'Run the sqlite dump after deploy'
task :sqlite_dump_dev do
rake = fetch(:rake, 'rake')
rails_env = fetch(:rails_env, 'development')

run "cd '#{current_path}' && #{rake} sqlite_dump RAILS_ENV=#{rails_env}"
end



Capistrano snippet to set Rails.env
capistrano_env.rb
set :rails_env, "test"
set :rack_env, rails_env

task :setup_env do
run "RACK_ENV=#{rails_env}"
run "RAILS_ENV=#{rails_env}"
run "echo 'RackEnv #{rails_env}' >> #{File.join(current_path, '.htaccess')}"
run "echo 'RailsEnv #{rails_env}' >> #{File.join(current_path, '.htaccess')}"
end

task :restart, :roles => :app, :except => { :no_release => true } do
deploy.setup_env
end



rails2.3.5 boot.rb

class Rails::Boot
def run
load_initializer

Rails::Initializer.class_eval do
def load_gems
@bundler_loaded ||= Bundler.require :default, Rails.env
end
end

Rails::Initializer.run(:set_load_path)
end
end



Use pry for rails console
# Launch Pry with access to the entire Rails stack.
# If you have Pry in your Gemfile, you can pass: ./script/console --irb=pry
# instead. If you don't, you can load it through the lines below :)
rails = File.join(Dir.getwd, 'config', 'environment.rb')

if File.exist?(rails) && ENV['SKIP_RAILS'].nil?
require rails

if Rails.version[0..0] == '2'
require 'console_app'
require 'console_with_helpers'
elsif Rails.version[0..0] == '3'
require 'rails/console/app'
require 'rails/console/helpers'
else
warn '[WARN] cannot load Rails console commands (Not on Rails 2 or 3?)'
end
end



  puts __FILE__ =>/app/controllers/productController.rb:
#以下两行是等价的
config_path = File.expand_path(File.join(File.dirname(__FILE__), "config.yml")) #expend_path 得到绝对路径
config_path = File.expand_path("../config.yml", __FILE__)


 #development.rb
$RAILS = {scheme: 'http', host: 'localhost', port: '3000' }
def $RAILS.scheme; $RAILS[:scheme]; end
def $RAILS.host; $RAILS[:host]; end
def $RAILS.port; $RAILS[:port]; end
def $RAILS.authority; "#{$RAILS.host}:#{$RAILS.port}"; end
def $RAILS.uri_root; "#{$RAILS.scheme}://#{$RAILS.host}:#{$RAILS.port}"; end


#init.rb
if Rails.env.production?
Rails::Application.middleware.use Hassle
end


if Rails.env.development? || Rails.env.test?
...
ENV['SKIP_RAILS_ADMIN_INITIALIZER'] = 'true'
...
end



 #autoload_paths.rb
["/rails_apps/my_app/app/controllers",
"/rails_apps/my_app/app/helpers",
"/rails_apps/my_app/app/models",
"/rails_plugins/my_engine/app/controllers",
"/rails_plugins/my_engine/app/helpers",
"/
rails_plugins/my_engine/app/models"]

 #cache.rb
#rails c production
Patient.all.each do |patient|
Rails.cache.delete("#{Rails.env}-patient-#{patient.id}")
end



#force lib reload in Rails #lib_reload.rb
load "#{Rails.root}/lib/yourfile.rb"

#Include_paths_rails_console.rb
include Rails.application.routes.url_helpers

 #routes.rb
if Rails.env.development? || Rails.env.test?
get '/getmein' => 'users#getmein'
end


#db_migrate_all.rake
namespace :db do
desc "Migrate all enviroments"
namespace :migrate do
task :all do
#current_rails_env = Rails.env
db_config = YAML::load(File.read(File.join(Rails.root, "/config/database.yml")))
db_config.keys.each do |e|
#Rails.env = e
#Rake::Task['db:migrate'].invoke
puts "migrating: #{e}"
system("rake db:migrate RAILS_ENV=#{e}")
puts "-------------"
end
#Rails.env = current_rails_env
end
end
end


 #Start Rails server from Rails console
require 'rails/commands/server'; server=Rails::Server.new;
Thread.new{server.start}

 #Add :assets group to Rails 4
Bundler.require(:default, ( :assets unless Rails.env == :production ), Rails.env)

 #how to start and stop custom daemon in Rails. According to Ryan Bates.
#custom_daemon_start_stop.rb
RAILS_ENV=development lib/daemons/mailer_ctl start
RAILS_ENV=development lib/daemons/mailer_ctl stop

#routes.rb
RailsApp::Application.routes.draw do
devise_for :members
mount RailsAdmin::Engine => '/manage', :as => 'rails_admin'
match ':controller(/:action(/:id(.:format)))',via: :get
end


#Rackup file for Rails 2.3.x projects (very useful for getting legacy apps running on pow.cx)
# Rails.root/config.ru
require "config/environment"
use Rails::Rack::LogTailer
use Rails::Rack::Static
run ActionController::Dispatcher.new



 
#Storing all the lib Ruby files in the constant RELOAD_LIBS
RELOAD_LIBS = Dir[Rails.root + 'lib/**/*.rb'] if Rails.env.development?





  #Helper pour modifier un field de form quand il y a un erreur  https://gist.github.com/gnepud/1780422
#form.html.erb
<% field_with_errors @zonage, :name do %>
... ...
<% end %>
#helper.rb
def field_with_errors(object, method, &block)
if block_given?
if object.errors[method].empty?
concat capture(&block)
else
add_error = capture(&block).gsub("control-group", "control-group error")
concat raw(add_error)
end
end
end



 # print SQL to STDOUT
if ENV.include?('RAILS_ENV') && !Object.const_defined?('RAILS_DEFAULT_LOGGER')
require 'logger'
RAILS_DEFAULT_LOGGER = Logger.new(STDOUT)
end


#Pry-rails add "reload!" method pry_config.rb
# write .pryrc
Pry.config.hooks.add_hook(:before_session, :add_rails_console_methods) do
self.extend Rails::ConsoleMethods if defined?(Rails::ConsoleMethods)
end


#Rack mounting with Rails app
#config.ru
require "config/environment"
require 'api'
rails_app = Rack::Builder.new do
use Rails::Rack::LogTailer
use Rails::Rack::Static
run ActionController::Dispatcher.new
end
run Rack::Cascade.new([ TourWrist::API, rails_app])


#Override logout_path for RailsAdmin.
#rails_admin_overrides.rb
# config/initializers/rails_admin_overrides.rb
module RailsAdminOverrides
def logout_path
"/admin/users/sign_out"
end
end
RailsAdmin::MainHelper.send :include, RailsAdminOverrides



#Incluir helpers rails en assets
#include_helpers_in_assets.rb
Rails.application.assets.context_class.class_eval do
include ActionView::Helpers
include Rails.application.routes.url_helpers
end



#IRails - run Rails server and generate from the Rails consolehttps://gist.github.com/cie/3228233
#irails.rb
# IRails - Run rails server and generator subcommands from the Rails console
#
# This is a solution based on http://blockgiven.tumblr.com/post/5161067729/rails-server
# Can be used to run rails server, rails generate from the Rails console thus
# speeding up Rails server startup to ~ 1 second.
#
# Usage:
# Rails.server to start the rails server
# Rails.generate to list generators
# Rails.generate "model", "user" to use a generator
# Rails.update "model", "user" to update the generated code
# Rails.destroy "model", "user" to remove the generated code
#
# NOTE: after Rails.server, you cannot use Control-C anymore in the console
# because it first stops the server, secondly stops the process
#

module Rails

def self.generate *args
require "rails/generators"
Rails::Generators.help && return if args.empty?
name = args.shift
args << "--orm=active_record" if args.none? {|a|a =~ /--orm/}
Rails::Generators.invoke name, args, :behavior => :invoke
end

def self.destroy *args
require "rails/generators"
Rails::Generators.help && return if args.empty?
name = args.shift
args << "--orm=active_record" if args.none? {|a|a =~ /--orm/}
Rails::Generators.invoke name, args, :behavior => :revoke
end

def self.update *args
require "rails/generators"
Rails::Generators.help && return if args.empty?
name = args.shift
args << "--orm=active_record" if args.none? {|a|a =~ /--orm/}
Rails::Generators.invoke name, args, :behavior => :skip
end

def self.server options={}
require "rails/commands/server"

Thread.new do
server = Rails::Server.new
server.options.merge options
server.start
end
end
end



# Because this app is based on rails_admin, we include the rails_admin
# application helpers as they are going to be needed by the rails_admin
# layout which we are reusing app/helpers/application_helper.rb#

module ApplicationHelper
include RailsAdmin::ApplicationHelper

end



# List out the Middleware being used by your Rails application
$ rake middleware

# in your environment.rb you can add/insert/swap
# items from your Middleware stack using:

config.middleware.use("MyMiddleware")

config.insert_after 'ActionController::Failsafe', MyMiddleware

config.middleware.swap 'Rails::Rack::Failsafe', MyFailsafer

# Generate a Rails Metal library using:
$ script/generate metal <name>

config.middleware.use 'CSSVariables', :templates => "#{RAILS_ROOT}/app/views/css"


if Rails.env.production?
Rails::Application.middleware.use Hassle
end

%w(middleware).each do |dir|
config.load_paths << #{RAILS_ROOT}/app/#{dir}
end



#client_side_validations
#01.gemfile
gem 'client_side_validations'
#02.sh
rails g client_side_validations:install

#03.erb
<%= javascript_include_tag "application", "rails.validations" %>

#04.erb
HTML+ERB
<%= form_for(@experience, :validate => true) do |f| %>

Include routes helpers in assetsInclude routes helpers in assets/
<% environment.context_class.instance_eval { include Rails.application.routes.url_helpers } %>



How to run rails server locally as production environment
rake db:migrate RAILS_ENV="production"
rails s -e production

zeus_cmd.sh
zeus s # to start rails server
zeus c # to start rails console
zeus test # to run tests
zeus generate model <name> # go generate modle




https://gist.github.com/TimothyKlim/2919040
https://gist.github.com/benqian/6257921 #Zero downtime deploys with unicorn + nginx + runit + rvm + chef
https://gist.github.com/seabre/5311826
https://gist.github.com/rmcafee/611058 #Flash Session Middleware
https://gist.github.com/DaniG2k/8883977
https://gist.github.com/wrburgess/4251366#Automatic ejs template
https://gist.github.com/LuckOfWise/3837668#twitter-bootstrap-rails
https://gist.github.com/vincentopensourcetaiwan/3303271#upload Images简介:使用 gem 'carrierwave' gem "rmagick" 构建图片上传显示
https://gist.github.com/tsmango/1030197 Rails::Generators 简介:一个简单在controller 生成器(Generators)
https://gist.github.com/jhirn/5811467 Generator for making a backbone model. Original author @daytonn
https://gist.github.com/richardsondx/5678906 FileUpload + Carrierwave + Nested Form + Javascript issue
https://gist.github.com/tjl2/1367060 Examining request objects
https://gist.github.com/sathishmanohar/4094666 Instructions to setup devise
https://gist.github.com/aarongough/802997
https://gist.github.com/fnando/8434842 #Render templates outside the controller in a Rails app
https://gist.github.com/sgeorgi/5664920 #Faye.md Generating events as Resque/Redis.jobs and publishing them to a faye websocket on the client. This is untested, but copied off a working project's implementation
https://gist.github.com/nshank/2150545#Filter by date
https://gist.github.com/jarsbe/5581413#Get Bootstrap and Rails error messages to play nicely together.
https://gist.github.com/apneadiving/1643990#gmaps4rails: Don't show map by default and load markers with ajax
https://gist.github.com/antage/5902790#Export all named routes from Ruby on Rails to Javascript (Rails 4 only)
https://gist.github.com/vincentopensourcetaiwan/3224356 #habtm_example
https://gist.github.com/kevin-shu/7672464 Rails後端筆記.md
https://gist.github.com/mkraft/3086918
https://gist.github.com/z8888q/2601233#Instructions for setting up the prepackaged Rails test environment
https://gist.github.com/onaclov2000/8209704
https://gist.github.com/wayneeseguin/165491#clear-rails-logs.sh
https://gist.github.com/ymainier/2912907#New rails project with bootstrap, simple_form and devise
https://gist.github.com/krisleech/4667962
https://gist.github.com/gelias/3571380
https://gist.github.com/rondale-sc/2156604
https://gist.github.com/patseng/3893616
https://gist.github.com/wnoguchi/7099085
https://gist.github.com/matthewrobertson/6129035
http://www.oschina.net/translate/active-record-serializers-from-scratch
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值