`
52jobs
  • 浏览: 11760 次
最近访客 更多访客>>
社区版块
存档分类
最新评论

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
分享到:
评论

相关推荐

    Ruby on Rails入门经典代码

    Ruby on Rails,简称Rails,是基于Ruby语言的一个开源Web应用程序框架,它遵循MVC(Model-View-Controller)架构模式,旨在使Web开发过程更加高效、简洁。本压缩包中的"Ruby on Rails入门经典代码"提供了新手学习...

    Rails项目源代码

    Ruby on Rails,通常简称为Rails,是一个基于Ruby编程语言的开源Web应用框架,遵循MVC(Model-View-Controller)架构模式。这个“Rails项目源代码”是一个使用Rails构建的图片分享网站的完整源代码,它揭示了如何...

    Beginning Ruby on rails 源代码

    Ruby on Rails(简称Rails)是一个基于Ruby语言的开源Web应用程序框架,它遵循MVC(Model-View-Controller)架构模式,旨在简化Web开发过程,提高开发效率。本资料包包含了《Beginning Ruby on Rails》一书的源代码...

    Rails3常用命令行命令

    Rails的scaffold命令是一个强大的工具,可以快速生成一套完整的CRUD(Create, Read, Update, Delete)界面,包括Model、View和Controller。例如,创建一个名为Person的资源: ```bash rails g scaffold person name...

    agile web development with rails2代码

    1. **MVC架构**:Rails遵循Model-View-Controller(MVC)设计模式,将业务逻辑、数据和用户界面分离,使得代码结构清晰,易于维护。 2. **动态路由**:Rails2的路由系统允许开发者通过资源定义来创建灵活的URL映射...

    Rails入门教程一(翻译).pdf

    Rails,全称为Ruby on Rails,是一个基于Ruby语言的开源Web应用程序框架,遵循MVC(Model-View-Controller)架构模式,用于构建数据库驱动的web应用。本教程是针对初学者设计的,旨在帮助他们快速掌握Rails的核心...

    web开发之rails最新调试通过购物车代码

    在Web开发领域,Ruby on Rails(简称Rails)是一种流行的开源框架,它基于MVC(Model-View-Controller)架构模式,用于快速构建高效、可维护的Web应用。本压缩包中的"web开发之rails最新调试通过购物车代码"是关于...

    ruby on rails 实例代码

    Ruby on Rails,简称Rails,是一个基于Ruby语言的开源Web应用程序框架,它遵循MVC(Model-View-Controller)架构模式,旨在使Web开发更高效、更简洁。在本实例代码中,我们将深入探讨如何利用Rails进行数据库操作,...

    Ruby On Rails开发实例-源代码

    Ruby on Rails(简称RoR或Rails)是一种基于Ruby语言的开源Web应用框架,它遵循Model-View-Controller(MVC)架构模式,旨在使Web开发更简洁、高效。本实例将帮助你深入理解和实践Rails的开发流程。 首先,让我们从...

    [Web开发敏捷之道--应用rails源代码][5]txt

    2. **Rails架构**:了解MVC模式,包括模型(Model)负责数据处理,视图(View)负责展示,控制器(Controller)作为模型和视图之间的桥梁。 3. **Rails生成器**:学习如何使用Rails的生成器快速创建控制器、模型、...

    提升Ruby on Rails性能的几个解决方案

    简介 Ruby On Rails 框架自它提出之日...Rails 是一个真正彻底的 MVC(Model-View-Controller) 框架,Rails 清楚地将你的模型的代码与你的控制器的应用逻辑从 View 代码中分离出来。Rails 开发人员很少或者可能从未遇到

    rails2.3.2

    Ruby on Rails(通常简称为 Rails)是一个基于 Ruby 语言的开源 Web 应用程序框架,它遵循 Model-View-Controller (MVC) 设计模式,用于构建数据库驱动的 Web 应用程序。Rails 强调“约定优于配置”(Convention ...

    Web开发敏捷之道--应用Rails进行敏捷Web开发 之 Depot代码。

    8. **app**:应用程序核心代码目录,包括模型(Model)、视图(View)和控制器(Controller),以及帮助器(Helper)、邮件器(Mailer)、通道(Channel)等。 9. **tmp**:临时文件目录,存储运行时生成的文件,如...

    AgileWebDevelopmentWithRails第三版代码

    1. **Rails基础**:Rails的核心是MVC架构,它将应用分为模型(Model)、视图(View)和控制器(Controller)三个部分,分别负责数据管理、用户界面展示和业务逻辑处理。书中可能通过实际代码展示了如何创建和管理这...

    Ruby on Rails实践

    在Ruby on Rails实践中,我们首先会接触到MVC(Model-View-Controller)架构模式。Model代表数据模型,负责业务逻辑和数据库交互;View负责展示数据,通常由HTML、CSS和JavaScript组成;Controller处理用户请求,并...

    征服 Ruby On Rails(源代码光盘)

    Rails中的MVC架构将应用程序分为三个主要部分:模型(Model)、视图(View)和控制器(Controller)。模型处理数据和业务逻辑,视图负责展示用户界面,控制器则协调模型和视图之间的交互。 2. Active Record Active...

    Rails 101S

    - **MVC架构与RESTful概念**:介绍模型(Model)、视图(View)、控制器(Controller)三者之间的关系以及RESTful API的设计原则。 - **深入解析Controller & Model**:进一步探讨Controller和Model的工作原理,理解如何...

    Ruby on Rails 教程 - 201406

    Ruby on Rails,简称ROR或Rails,是一款基于Ruby语言的开源Web应用框架,它遵循Model-View-Controller(MVC)架构模式,旨在提高开发效率和代码可读性。本教程“Ruby on Rails 教程 - 201406”可能是针对2014年6月时...

    rails指南 中文版

    Ruby on Rails(简称Rails)是一个基于Ruby语言的开源Web应用框架,它遵循MVC(Model-View-Controller)架构模式,强调“约定优于配置”(Conventions over Configuration)和“Don't Repeat Yourself”(DRY,不要...

Global site tag (gtag.js) - Google Analytics