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
发表评论
-
rails 小技巧
2014-02-23 22:55 539#Rails Tip 1 Actions Are Method ... -
ruby 小技巧
2014-02-23 21:18 854#Track 1: The C in MVC #irb Mi ... -
rails bash
2014-02-22 21:48 5711、一个完整的rails app自动生成bash 引用#!/ ... -
实用工具--rails 命令、generator
2014-02-22 20:52 9491、rails 基本 rails new rails-boo ... -
rails 版本 更新/升级 release note
2014-02-22 14:02 516升级到 Rails 4,你的应用需要准备什么? 升 ... -
理解rails gems plugins
2014-02-22 13:06 594#33 Making a Plugin 引用注意 这种手法,可 ... -
日期 、路由辅助方法
2014-02-22 11:48 513#31 Formatting Time 方法一: Task ... -
rails 调试
2014-02-23 22:57 462#24 The Stack Trace A plugin c ... -
Authentication 用户登录 用户权限相关
2014-02-21 21:20 582引用 # 19Where Administration Goe ... -
ActiveRecord
2014-02-21 20:39 944ActiveRecord 4新特性 http://www.os ... -
工作相关
2014-02-21 20:27 489# 工作经历: 2年制造业ERP开发及管理经验 2年旅游信息化 ... -
rails 开发工具相关
2014-02-21 20:14 428#使用TextMate进行Ruby On Rails开发推荐插 ... -
rails view session layout
2014-02-21 19:00 624#208 erb-blocks 简介:在erb中使用block ...
相关推荐
简介 Ruby On Rails 框架自它提出之日...Rails 是一个真正彻底的 MVC(Model-View-Controller) 框架,Rails 清楚地将你的模型的代码与你的控制器的应用逻辑从 View 代码中分离出来。Rails 开发人员很少或者可能从未遇到
Rather than toss you into the middle of the framework’s Model-View-Controller architecture, as many books do, Learning Rails 5 begins with the foundations of the Web you already know. You’ll learn ...
在日前结束的Kungfu Rails大会上,来自台湾的著名Rails人张文钿(ihower)为大家带来了一个关于Rails最佳实践的分享,演讲结束后Rails3的核心开发者Yehuda Katz主动索要幻灯片,其内容之精彩已不言而喻。 会后,...
rails, Ruby on Rails 欢迎使用 RailsRails 是一个web应用程序框架,它包括根据 Model-View-Controller ( MVC ) Pattern 创建数据库备份的web应用程序所需的所有内容。理解 MVC Pattern 是理解 Rai
upmin-admin 是一个为 Rails 应用开发的开源管理框架。用来管理 Rails 应用中各种对象(如 Model、View 和 Controller )。 标签:upmin
Rather than toss you into the middle of the framework’s Model-View-Controller architecture, as many books do, Learning Rails 5 begins with the foundations of the Web you already know. You’ll learn ...
Rather than toss you into the middle of the framework’s Model-View-Controller architecture, as many books do, Learning Rails 5 begins with the foundations of the Web you already know. You’ll learn ...
Ruby on Rails的性能调优方案研究,张淼森,杨杰,Ruby on Rails 框架自它提出之日起就受到广泛关注。由于Rails框架基于MVC(Model-View-Controller) 模型,可以清楚地将模型层的代码与控制层的应
准的编程模式,比如ActiveRecord 以及Model-View-Controller。它重用很多已经存在 的Ruby 库(比如Rake和ERb)。Rails 的功能在于集成这些标准的技术自动化完成任务, 并且会断言合理的默认行为。
譬如说,所有的Rails 应用都采用了“模型-视图-控制器”(Model-View-Controller, MVC) 架构。Java 开发者都很熟悉MVC 框架,例如Tapestry 和struts。但Rails 把MVC 贯彻得更彻底: 当你用Rails 开发时,每一块代码该...
Rails is a web-application framework that includes everything needed to create database-backed web applications according to the Model-View-Controller (MVC) pattern.
其中, Rails 是 Ruby 中最有名的 Web 应用程序开发框架,它是 一个开放源代码的 MVC (Model-View-Controller)框架。 Rails 采 用了“约定大于配置”的理念,内置了很多常用的功能, 如路由、 数据库访问和 HTML ...
Kales run on top of Ktor and uses a Model-View-Controller architecture. Database access is done via JDBI and configured from a database.yml resource file (similar to Rails). More ...
Form数据库基础 PostgreSQLMVC 设计模式 Model-View-Controller风格化 Bootstrap Styling闪烁消息 Flash Message邮件发送 Sending EmailUserHub 项目开发流程用户模型 User Model路由概念 Route
Griffon has adopted many of those languages’ and frameworks’ best practices, including Model-View-Controller, convention-over-configuration, a modern dynamic language (Groovy), domain-specific ...
Ruby 语言常以其灵活性为人所称道。正如 Dick Sites 所言,您可以 “为了编程而编程”。...例如,Ruby on Rails 基于模型-视图-控制器(Model-View-Controller,MVC)模式,这意味着大多数 Rails 应用程序都
Kamigo 让你开发Chatbot 就跟开发网站一样容易,甚至可以同时开发网站以及Chatbot 介面,共用Controller 和Model,只需要针对Chatbot 实作View。 Kamigo 提供了重要的generator,让你开发聊天机器人时可以快的跟飞...
Ruby on Rails,也称为RoR或Rails,是一种遵循Model View Controller(MVC)模式范例,以Ruby编程语言编写的开源Web应用程序框架。 目录 安装 首先在您的计算机上克隆存储库 git clone ...