Rails源码研究之ActiveRecord:一,基本架构、CRUD封装与数据库连接

Rails的ORM框架ActiveRecord是马大叔的[url=http://www.martinfowler.com/eaaCatalog/activeRecord.html]ActiveRecord模式[/url]的实现+associations+[url=http://wiki.rubyonrails.org/rails/pages/SingleTableInheritance]SingleTableInheritance[/url]
ActiveRecord的作者也是Rails的作者--David Heinemeier Hansson
ActiveRecord的key features:
1,零Meta Data,不需要XML配置文件
2,Database Support,现在支持mysql postgresql sqlite firebird sqlserver db2 oracle sybase openbase frontbase,[url=http://wiki.rubyonrails.org/rails/pages/New+database+adapter]写一个新的database adapter[/url]不会超过100行代码
3,线程安全,本地Ruby Web服务器,如WEBrick/Cerise,用线程处理请求
4,速度快,对100个对象循环查找一个值做benchmark,速度为直接数据库查询速度的50%
5,事务支持,使用事务来确保级联删除自动执行,同时也支持自己写事务安全的方法
6,简洁的关联,使用natural-language macros,如has_many、belongs_to
7,内建validations支持
8,自定义值对象

让我们深入研读一下ActiveRecord的核心源码
1,activerecord-1.15.3\lib\active_record.rb:
[code]
$:.unshift(File.dirname(__FILE__)) unless
$:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__)))

unless defined?(ActiveSupport)
begin
$:.unshift(File.dirname(__FILE__) + "/../../activesupport/lib")
require 'active_support'
rescue LoadError
require 'rubygems'
gem 'activesupport'
end
end

require 'active_record/base'
require 'active_record/observer'
require 'active_record/validations'
require 'active_record/callbacks'
require 'active_record/reflection'
require 'active_record/associations'
require 'active_record/aggregations'
require 'active_record/transactions'
require 'active_record/timestamp'
require 'active_record/acts/list'
require 'active_record/acts/tree'
require 'active_record/acts/nested_set'
require 'active_record/locking/optimistic'
require 'active_record/locking/pessimistic'
require 'active_record/migration'
require 'active_record/schema'
require 'active_record/calculations'
require 'active_record/xml_serialization'
require 'active_record/attribute_methods'

ActiveRecord::Base.class_eval do
include ActiveRecord::Validations
include ActiveRecord::Locking::Optimistic
include ActiveRecord::Locking::Pessimistic
include ActiveRecord::Callbacks
include ActiveRecord::Observing
include ActiveRecord::Timestamp
include ActiveRecord::Associations
include ActiveRecord::Aggregations
include ActiveRecord::Transactions
include ActiveRecord::Reflection
include ActiveRecord::Acts::Tree
include ActiveRecord::Acts::List
include ActiveRecord::Acts::NestedSet
include ActiveRecord::Calculations
include ActiveRecord::XmlSerialization
include ActiveRecord::AttributeMethods
end

unless defined?(RAILS_CONNECTION_ADAPTERS)
RAILS_CONNECTION_ADAPTERS = %w( mysql postgresql sqlite firebird sqlserver db2 oracle sybase openbase frontbase )
end

RAILS_CONNECTION_ADAPTERS.each do |adapter|
require "active_record/connection_adapters/" + adapter + "_adapter"
end

require 'active_record/query_cache'
require 'active_record/schema_dumper'
[/code]
首先$:.unshift一句将当前文件加入动态库路径,然后确保加载ActiveSupport
然后将active_record/base/observer/validations.../attribute_methods等子目录下的文件require进来
然后用ActiveRecord::Base.class_eval将ActiveRecord::Validations/Locking/.../AttributeMethods等子模块include进来
RAILS_CONNECTION_ADAPTERS定义了ActiveRecord支持的database adapters的名字数组,然后循环将每个adapter文件require进来
最后将query_cache和schema_dumper这两个文件require进来

2,activerecord-1.15.3\lib\active_record\base.rb:
[code]
module ActiveRecord

class Base

class << self # Class methods

def find(*args)
options = extract_options_from_args!(args)
validate_find_options(options)
set_readonly_option!(options)

case args.first
when :first then find_initial(options)
when :all then find_every(options)
else find_from_ids(args, options)
end
end

def find_by_sql(sql)
connection.select_all(sanitize_sql(sql), "#{name} Load").collect! { |record| instantiate(record) }
end

def exists?(id_or_conditions)
!find(:first, :conditions => expand_id_conditions(id_or_conditions)).nil?
rescue ActiveRecord::ActiveRecordError
false
end

def create(attributes = nil)
if attributes.is_a?(Array)
attributes.collect { |attr| create(attr) }
else
object = new(attributes)
scope(:create).each { |att,value| object.send("#{att}=", value) } if scoped?(:create)
object.save
object
end
end

def update(id, attributes)
if id.is_a?(Array)
idx = -1
id.collect { |id| idx += 1; update(id, attributes[idx]) }
else
object = find(id)
object.update_attributes(attributes)
object
end
end

def delete(id)
delete_all([ "#{connection.quote_column_name(primary_key)} IN (?)", id ])
end

def destroy(id)
id.is_a?(Array) ? id.each { |id| destroy(id) } : find(id).destroy
end

def update_all(updates, conditions = nil)
sql = "UPDATE #{table_name} SET #{sanitize_sql(updates)} "
add_conditions!(sql, conditions, scope(:find))
connection.update(sql, "#{name} Update")
end

def destroy_all(conditions = nil)
find(:all, :conditions => conditions).each { |object| object.destroy }
end

def delete_all(conditions = nil)
sql = "DELETE FROM #{table_name} "
add_conditions!(sql, conditions, scope(:find))
connection.delete(sql, "#{name} Delete all")
end

def count_by_sql(sql)
sql = sanitize_conditions(sql)
connection.select_value(sql, "#{name} Count").to_i
end

private

def find_initial(options)
options.update(:limit => 1) unless options[:include]
find_every(options).first
end

def find_every(options)
records = scoped?(:find, :include) || options[:include] ?
find_with_associations(options) :
find_by_sql(construct_finder_sql(options))

records.each { |record| record.readonly! } if options[:readonly]

records
end

def find_from_ids(ids, options)
expects_array = ids.first.kind_of?(Array)
return ids.first if expects_array && ids.first.empty?

ids = ids.flatten.compact.uniq

case ids.size
when 0
raise RecordNotFound, "Couldn't find #{name} without an ID"
when 1
result = find_one(ids.first, options)
expects_array ? [ result ] : result
else
find_some(ids, options)
end
end

def find_one(id, options)
conditions = " AND (#{sanitize_sql(options[:conditions])})" if options[:conditions]
options.update :conditions => "#{table_name}.#{connection.quote_column_name(primary_key)} = #{quote_value(id,columns_hash[primary_key])}#{conditions}"

if result = find_every(options).first
result
else
raise RecordNotFound, "Couldn't find #{name} with ID=#{id}#{conditions}"
end
end

def find_some(ids, options)
conditions = " AND (#{sanitize_sql(options[:conditions])})" if options[:conditions]
ids_list = ids.map { |id| quote_value(id,columns_hash[primary_key]) }.join(',')
options.update :conditions => "#{table_name}.#{connection.quote_column_name(primary_key)} IN (#{ids_list})#{conditions}"

result = find_every(options)

if result.size == ids.size
result
else
raise RecordNotFound, "Couldn't find all #{name.pluralize} with IDs (#{ids_list})#{conditions}"
end
end

def method_missing(method_id, *arguments)
if match = /^find_(all_by|by)_([_a-zA-Z]\w*)$/.match(method_id.to_s)
finder, deprecated_finder = determine_finder(match), determine_deprecated_finder(match)

attribute_names = extract_attribute_names_from_match(match)
super unless all_attributes_exists?(attribute_names)

attributes = construct_attributes_from_arguments(attribute_names, arguments)

case extra_options = arguments[attribute_names.size]
when nil
options = { :conditions => attributes }
set_readonly_option!(options)
ActiveSupport::Deprecation.silence { send(finder, options) }

when Hash
finder_options = extra_options.merge(:conditions => attributes)
validate_find_options(finder_options)
set_readonly_option!(finder_options)

if extra_options[:conditions]
with_scope(:find => { :conditions => extra_options[:conditions] }) do
ActiveSupport::Deprecation.silence { send(finder, finder_options) }
end
else
ActiveSupport::Deprecation.silence { send(finder, finder_options) }
end

else
ActiveSupport::Deprecation.silence do
send(deprecated_finder, sanitize_sql(attributes), *arguments[attribute_names.length..-1])
end
end
elsif match = /^find_or_(initialize|create)_by_([_a-zA-Z]\w*)$/.match(method_id.to_s)
instantiator = determine_instantiator(match)
attribute_names = extract_attribute_names_from_match(match)
super unless all_attributes_exists?(attribute_names)

attributes = construct_attributes_from_arguments(attribute_names, arguments)
options = { :conditions => attributes }
set_readonly_option!(options)

find_initial(options) || send(instantiator, attributes)
else
super
end
end

def extract_attribute_names_from_match(match)
match.captures.last.split('_and_')
end

def construct_attributes_from_arguments(attribute_names, arguments)
attributes = {}
attribute_names.each_with_index { |name, idx| attributes[name] = arguments[idx] }
attributes
end

protected

def sanitize_sql(condition)
case condition
when Array; sanitize_sql_array(condition)
when Hash; sanitize_sql_hash(condition)
else condition
end
end

def sanitize_sql_hash(attrs)
conditions = attrs.map do |attr, value|
"#{table_name}.#{connection.quote_column_name(attr)} #{attribute_condition(value)}"
end.join(' AND ')

replace_bind_variables(conditions, expand_range_bind_variables(attrs.values))
end

def sanitize_sql_array(ary)
statement, *values = ary
if values.first.is_a?(Hash) and statement =~ /:\w+/
replace_named_bind_variables(statement, values.first)
elsif statement.include?('?')
replace_bind_variables(statement, values)
else
statement % values.collect { |value| connection.quote_string(value.to_s) }
end
end

alias_method :sanitize_conditions, :sanitize_sql

end

public

def save
create_or_update
end

def save!
create_or_update || raise(RecordNotSaved)
end

def destroy
unless new_record?
connection.delete <<-end_sql, "#{self.class.name} Destroy"
DELETE FROM #{self.class.table_name}
WHERE #{connection.quote_column_name(self.class.primary_key)} = #{quoted_id}
end_sql
end

freeze
end

def update_attribute(name, value)
send(name.to_s + '=', value)
save
end

def update_attributes(attributes)
self.attributes = attributes
save
end

def update_attributes!(attributes)
self.attributes = attributes
save!
end

private

def create_or_update
raise ReadOnlyRecord if readonly?
result = new_record? ? create : update
result != false
end

def update
connection.update(
"UPDATE #{self.class.table_name} " +
"SET #{quoted_comma_pair_list(connection, attributes_with_quotes(false))} " +
"WHERE #{connection.quote_column_name(self.class.primary_key)} = #{quote_value(id)}",
"#{self.class.name} Update"
)
end

def create
if self.id.nil? && connection.prefetch_primary_key?(self.class.table_name)
self.id = connection.next_sequence_value(self.class.sequence_name)
end

self.id = connection.insert(
"INSERT INTO #{self.class.table_name} " +
"(#{quoted_column_names.join(', ')}) " +
"VALUES(#{attributes_with_quotes.values.join(', ')})",
"#{self.class.name} Create",
self.class.primary_key, self.id, self.class.sequence_name
)

@new_record = false
id
end

def method_missing(method_id, *args, &block)
method_name = method_id.to_s
if @attributes.include?(method_name) or
(md = /\?$/.match(method_name) and
@attributes.include?(query_method_name = md.pre_match) and
method_name = query_method_name)
define_read_methods if self.class.read_methods.empty? && self.class.generate_read_methods
md ? query_attribute(method_name) : read_attribute(method_name)
elsif self.class.primary_key.to_s == method_name
id
elsif md = self.class.match_attribute_method?(method_name)
attribute_name, method_type = md.pre_match, md.to_s
if @attributes.include?(attribute_name)
__send__("attribute#{method_type}", attribute_name, *args, &block)
else
super
end
else
super
end
end

end

end
[/code]
base.rb这个文件比较大,它首先定义了Base类的Class Method,包括find、find_by_sql、create、update、destroy等
然后定义了一些private方法,如find_initial、find_every、find_from_ids等方法,它们供public的find方法调用
不出所料,private作用域里还定义了method_missing方法,它支持find_by_username、find_by_username_and_password、find_or_create_by_username等动态增加的方法
protected作用域里定义了sanitize_sql等辅助方法,这样子类(即我们的Model)中也可以使用这些protected方法
然后定义了Base类的public的Instance Method,如save、destroy、update_attribute、update_attributes等
然后定义了Base类的private的Instance Method,如供public的save方法调用的create_or_update、create、update等方法
然后定义了private的method_missing实例方法,供本类内其他实例方法访问本类的attributes

3,activerecord-1.15.3\lib\active_record\connection_adapters\abstract\connection_specification.rb:
[code]
module ActiveRecord
class Base
class ConnectionSpecification
attr_reader :config, :adapter_method
def initialize (config, adapter_method)
@config, @adapter_method = config, adapter_method
end
end

class << self

def connection
self.class.connection
end

def self.establish_connection(spec = nil)
case spec
when nil
raise AdapterNotSpecified unless defined? RAILS_ENV
establish_connection(RAILS_ENV)
when ConnectionSpecification
clear_active_connection_name
@active_connection_name = name
@@defined_connections[name] = spec
when Symbol, String
if configuration = configurations[spec.to_s]
establish_connection(configuration)
else
raise AdapterNotSpecified, "#{spec} database is not configured"
end
else
spec = spec.symbolize_keys
unless spec.key?(:adapter) then raise AdapterNotSpecified, "database configuration does not specify adapter" end
adapter_method = "#{spec[:adapter]}_connection"
unless respond_to?(adapter_method) then raise AdapterNotFound, "database configuration specifies nonexistent #{spec[:adapter]} adapter" end
remove_connection
establish_connection(ConnectionSpecification.new(spec, adapter_method))
end
end
end
end
[/code]
connection_specification.rb文件定义了ActiveRecord::Base建立获取数据库连接相关的方法

4,activerecord-1.15.3\lib\active_record\connection_adapters\mysql_adapter.rb:
[code]
module ActiveRecord
class Base
def self.mysql_connection(config)
config = config.symbolize_keys
host = config[:host]
port = config[:port]
socket = config[:socket]
username = config[:username]
password = config[:password]

if config.has_key?(:database)
database = config[:database]
else
raise ArgumentError, "No database specified. Missing argument: database."
end

require_mysql
mysql = Mysql.init
mysql.ssl_set(config[:sslkey], config[:sslcert], config[:sslca], config[:sslcapath], config[:sslcipher]) if config[:sslkey]

ConnectionAdapters::MysqlAdapter.new(mysql, logger, [host, username, password, database, port, socket], config)
end
end

module ConnectionAdapters
class MysqlAdapter < AbstractAdapter
def initialize(connection, logger, connection_options, config)
super(connection, logger)
@connection_options, @config = connection_options, config

connect
end

def execute(sql, name = nil) #:nodoc:
log(sql, name) { @connection.query(sql) }
rescue ActiveRecord::StatementInvalid => exception
if exception.message.split(":").first =~ /Packets out of order/
raise ActiveRecord::StatementInvalid, "'Packets out of order' error was received from the database. Please update your mysql bindings (gem install mysql) and read http://dev.mysql.com/doc/mysql/en/password-hashing.html for more information. If you're on Windows, use the Instant Rails installer to get the updated mysql bindings."
else
raise
end
end

def insert(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) #:nodoc:
execute(sql, name = nil)
id_value || @connection.insert_id
end

def update(sql, name = nil) #:nodoc:
execute(sql, name)
@connection.affected_rows
end

private
def connect
encoding = @config[:encoding]
if encoding
@connection.options(Mysql::SET_CHARSET_NAME, encoding) rescue nil
end
@connection.ssl_set(@config[:sslkey], @config[:sslcert], @config[:sslca], @config[:sslcapath], @config[:sslcipher]) if @config[:sslkey]
@connection.real_connect(*@connection_options)
execute("SET NAMES '#{encoding}'") if encoding

execute("SET SQL_AUTO_IS_NULL=0")
end
end
end
end
[/code]
这个文件是mysql的数据库adapter的例子,其中mysql_connection->connect->real_connect方法会在establish_connection中调用

5,activerecord-1.15.3\lib\active_record\vendor\mysql.rb:
[code]
class Mysql

def initialize(*args)
@client_flag = 0
@max_allowed_packet = MAX_ALLOWED_PACKET
@query_with_result = true
@status = :STATUS_READY
if args[0] != :INIT then
real_connect(*args)
end
end

def real_connect(host=nil, user=nil, passwd=nil, db=nil, port=nil, socket=nil, flag=nil)
@server_status = SERVER_STATUS_AUTOCOMMIT
if (host == nil or host == "localhost") and defined? UNIXSocket then
unix_socket = socket || ENV["MYSQL_UNIX_PORT"] || MYSQL_UNIX_ADDR
sock = UNIXSocket::new(unix_socket)
@host_info = Error::err(Error::CR_LOCALHOST_CONNECTION)
@unix_socket = unix_socket
else
sock = TCPSocket::new(host, port||ENV["MYSQL_TCP_PORT"]||(Socket::getservbyname("mysql","tcp") rescue MYSQL_PORT))
@host_info = sprintf Error::err(Error::CR_TCP_CONNECTION), host
end
@host = host ? host.dup : nil
sock.setsockopt Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true
@net = Net::new sock

a = read
@protocol_version = a.slice!(0)
@server_version, a = a.split(/\0/,2)
@thread_id, @scramble_buff = a.slice!(0,13).unpack("La8")
if a.size >= 2 then
@server_capabilities, = a.slice!(0,2).unpack("v")
end
if a.size >= 16 then
@server_language, @server_status = a.slice!(0,3).unpack("cv")
end

flag = 0 if flag == nil
flag |= @client_flag | CLIENT_CAPABILITIES
flag |= CLIENT_CONNECT_WITH_DB if db

@pre_411 = (0 == @server_capabilities & PROTO_AUTH41)
if @pre_411
data = Net::int2str(flag)+Net::int3str(@max_allowed_packet)+
(user||"")+"\0"+
scramble(passwd, @scramble_buff, @protocol_version==9)
else
dummy, @salt2 = a.unpack("a13a12")
@scramble_buff += @salt2
flag |= PROTO_AUTH41
data = Net::int4str(flag) + Net::int4str(@max_allowed_packet) +
([8] + Array.new(23, 0)).pack("c24") + (user||"")+"\0"+
scramble41(passwd, @scramble_buff)
end

if db and @server_capabilities & CLIENT_CONNECT_WITH_DB != 0
data << "\0" if @pre_411
data << db
@db = db.dup
end
write data
pkt = read
handle_auth_fallback(pkt, passwd)
ObjectSpace.define_finalizer(self, Mysql.finalizer(@net))
self
end

alias :connect :real_connect

def real_query(query)
command COM_QUERY, query, true
read_query_result
self
end

def query(query)
real_query query
if not @query_with_result then
return self
end
if @field_count == 0 then
return nil
end
store_result
end

end
[/code]
其中mysql.rb里的real_connect定义了Mysql数据库真正建立连接的方法

这次主要研究了ActiveRecord的基本架构、CRUD方法的封装以及以Mysql为例子的数据库连接相关的代码,歇会再聊,咳咳
破解现代反爬虫:JS加密、OB混淆与CSS反爬的实战攻防分析 摘要: 随着反爬技术的升级,JS加密、OB混淆和CSS反爬成为主流防护手段,阻碍传统爬虫获取数据。本文解析了这些技术的工作原理,并提出破解策略:通过模拟浏览器(如Selenium、Puppeteer)执行动态JS,逆向混淆代码,以及利用开发者工具突破CSS隐藏。针对复杂防护,开发者需结合技术分析与工具应用,如API接口抓取、动态渲染破解等,以应对不断演进的反爬机制。未来,爬虫攻防将持续升级,需保持技术敏锐性。 阅读详情

相关推荐

BOSS直聘数据采集实战:八爪鱼工具高效爬取职位信息的完整指南

本文提供了一份使用八爪鱼采集器高效爬取BOSS直聘职位信息的完整实战指南。针对非技术用户,详细讲解了从软件安装、网址规律分析到流程配置、数据导出的每一步操作,并分享了提升采集稳定性的高级设置与避坑技巧,帮助用户轻松实现数据采集自动化。

weixin_29061509的博客 1481

Rails源代码研读之ActiveRecord研读

ActiveRecord 的 connection_poll 使用了 Monit       class Reaper attr_reader :pool, :frequency def initialize(pool, frequency) @pool = pool @frequency = frequency

何旭东chucai的专栏 1097

Rails详细介绍(八)ActiveRecord基础(列和属性)

    ActiveRecord中的一个对象相当于数据库中表的一行,对象的属性对应于表的列,ActiveRecord在运行时来确定这些对应关系 。我们的orders表可能使用下面的sql来创建: create table orders ( id int not null auto_increment, name varchar(100) not null, email varchar(25...

Ruby爱好者 472

ESP32-S3 + TB6600驱动42步进电机:从基础接线到AccelStepper库平滑加减速实战

本文详细介绍了如何使用ESP32-S3开发板和TB6600驱动器控制42步进电机,从基础接线到利用AccelStepper库实现平滑加减速控制。内容涵盖硬件连接、基础驱动代码、AccelStepper库的安装与参数调优,以及高级技巧与故障排除,帮助创客实现工业级精准控制。

weixin_42632434的博客 292

内容分析指南(The Content Analysis Guidebook Second Edition)

The Content Analysis Guidebook Second Edition Kimberly A. Neuendorf Cleveland State University 下载地址: 用于分析交互媒体(社交媒体等)中的内容 目录 Contents List of Boxes List of Tables and Figures Preface Acknowled...

NULL 2174

深入分析rails数据库连接流程

第一部分: Method 1) defself.establish_connection(spec=nil)casespec#1whennilraiseAdapterNotSpecifiedunlessdefined?RAILS_ENVestablish_connection(RAILS_ENV)whenConnectionSpecification #2clear_active_c...

编程资料大全 203

结合 Conda 手动安装 RepeatMasker

RepeatMasker 是一个广泛使用的生物信息学工具,用于识别和屏蔽(mask)基因组序列中的 重复序列(repeats) 。在使用过程中需要调用重复序列数据库(Repbase 和 Dfam),如果使用Conda安装的话会出现许多问题,因此推荐手动安装。在此记录我手动安装RepeatMasker的流程,希望对各位同学有所帮助。

m0_65437087的博客 2544

Rails5中AR的新特性

Rails5正式版, 终于经过众多测试版后,与我们见面了,本文就来介绍一下,在Rails5中有哪些关于ActiveRecord相关的新特性,以便能够更好的使用Rails5进行开发。 ApplicationRecord 在Rails4中所有的模型都继承自ActiveRecord::Base,不过在Rails5中新引进了一个叫ApplicationRecord的类,存放在: app/mode

zh538438的博客 659

基于simulink的低通滤波器(Low-pass Filter, LPF)

摘要:本文详细介绍了如何在Simulink中搭建低通滤波器进行噪声抑制仿真。通过定义系统需求(50Hz信号+250Hz噪声)、添加信号源、设计6阶巴特沃斯低通滤波器(截止频率100Hz)、连接各模块并配置仿真参数,最终实现高频噪声的有效滤除。该教程包含从模型创建到结果分析的完整流程,为信号处理系统开发提供了基础框架,并可进一步扩展为自适应滤波等高级应用。所需MATLAB版本为R2023a及以上,需安装Simulink和DSPSystemToolbox。

amy_mhd的博客 1310

QT Android开发之Android端usb调试模式设置与问题解决

QT Android开发之Android端usb调试模式设置与问题解决 一.QT android开发android端usb调试模式设置 QT android开发环境搭建完成后,android设备需要打开usb调试模式才能正常连接,下面以小米ipad为例进行设置(其他手机和ipad设置方法类似) 二.小米ipad打开usb调试模式 1.设置----我的设备-----全部参数信息-----OS版本---点击这里6次以上就进入开发者模式。

热土程序园,利他愉己~ 1143

RubyOnRailsStart —— Ruby on Rails 入门最佳开源实战项目

是一个为Ruby on Rails 初学者精心打造的开源入门项目,基于经典教材《Ruby on Rails 实战圣经》一步步实现所有示例代码与功能,让你在实战中彻底掌握Rails MVC 架构CRUD 开发分页插件局部模板等核心技能。无论你是零基础入门 Ruby on Rails,还是想通过 Demo 快速回顾 Rails 开发流程,这个仓库都能帮你快速上手,并且方便随时查阅、参考和复用。

2504_90369923的博客 363

使用 Python 调用 GitHub REST API 爬取 GitHub 仓库信息(完整指南)

GitHub 提供了功能强大的 REST API,允许开发者通过编程方式访问 GitHub 上的仓库、用户、提交记录、PR(Pull Request)等信息。GitHub REST API 是 GitHub 官方提供的 API 接口,支持通过 HTTP 请求来操作 GitHub 上的资源。在本文中,我们将使用 Python 编写一个完整的爬虫程序,调用 GitHub 的 REST API 来爬取 GitHub 仓库的信息。目前 GitHub 使用的主要是 v3 版本的 REST API。

2201_76125261的博客 1117

Sinatra vs Rails:轻量级Ruby框架如何提升开发效率?

在Ruby Web开发领域,开发者常常面临框架选择的难题。**Sinatra**作为轻量级Ruby框架的代表,以其简洁灵活的特性,为开发者提供了一种不同于Rails的高效开发体验。本文将深入对比Sinatra与Rails的核心差异,帮助你理解何时选择轻量级框架能显著提升开发效率。 ## 🚀 框架定位:轻量级与全栈的对决 Sinatra的设计理念是**"Classy web-developme

gitblog_00628的博客 606

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

Ruby on Rails极速开发秘诀:如何在1024小时内交付50个功能模块

掌握Ruby on Rails 1024 快速开发案例,揭秘如何在1024小时内高效交付50个功能模块。适用于敏捷开发与创业项目,结合代码生成、自动化测试与模块复用技术,显著提升开发效率。实战方法论值得收藏。

FastCompile的博客 1061

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

深入解析Ruby on Rails框架:核心组件与开发实践

Ruby on Rails是一个基于MVC架构的全栈Web开发框架,采用Ruby语言编写。其核心设计哲学'约定优于配置'显著提升了开发效率,通过Active Record实现优雅的ORM映射,Action Controller处理Web请求,以及Action View进行动态模板渲染。Rails框架特别适合快速开发复杂的数据库驱动应用,广泛应用于电商平台、内容管理系统等场景。通过内置的Active Job和缓存机制,Rails也能有效处理高并发需求。掌握Rails的核心组件如Active Record和Ac

aizexi2652的博客 384

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

Ruby on Rails 1024项目实战全记录(千行代码引爆开发效率)

掌握Ruby on Rails 1024快速开发案例,轻松实现高效建站与原型迭代。本文记录千行代码实战全过程,涵盖RESTful设计、自动化部署与性能优化技巧,适用于创业项目与中小型系统开发,显著提升效率,值得收藏。

FastDebug的博客 883

Ruby on Rails——一个完整的例子(二)

我们可以使用表单生成器来创建表单。在这里我们先使用以下rails为我们提供的form_with方法,把它加入到之前创建的文件app/views/articles/new.html.erb中: &lt;%= form_with scope: :article, local: true do |form| %&gt; &lt;p&gt; &lt;%= form.label :titl...

wufeng_no1的博客 1812

SQLAlchemy-mixins核心功能解析:从CRUD操作到智能查询的7个实用技巧

SQLAlchemy-mixins 是一个强大的Python库,它为SQLAlchemy ORM提供了类似Active Record模式的便捷功能,让数据库操作变得更加简单高效。无论你是SQLAlchemy的新手还是经验丰富的开发者,这个库都能显著提升你的开发效率。本文将深入解析SQLAlchemy-mixins的7个核心实用技巧,帮助你快速掌握这个强大的工具。 ## 🚀 快速入门:安装与基础

gitblog_00718的博客 788

.NET技术演进与开发者成长心法:兼容性、源码阅读与跨栈建模

编程语言与运行时框架的演进,本质是工程哲学在兼容性、抽象能力与可维护性之间的持续权衡。.NET的向后兼容设计并非技术保守,而是基于二进制兼容、源码稳定与运行时沙箱的系统性保障;async/await等语法糖背后是状态机与IOCP的底层协同,揭示了异步编程的本质逻辑;而将TPL与GCD、MVC路由与Rails路由对照理解,则体现了跨技术栈建模的价值——它让知识从离散点升级为可迁移的网络。这种‘读源码→解框架→连生态’的学习路径,正是中高级开发者突破技术瓶颈、构建长期竞争力的核心方法论。

437

Clojure学习——持久化框架clj-record

clj-record是仿Ruby on Rails ActiveRecord的一个持久化框架。项目源码在github上,使用说明写的很坑爹,就不能写个能跑起来的代码么。只是断断续续学了不久clojure,被逼去看源码,试了好几次,总算写出了能跑起来的代码。 [b]添加依赖[/b] [code="clojure"] [mysql/mysql-connector-java "5.1.21"]...

nil 225

什么是Rails ActiveRecord

Active Record is the M in MVC — the model — which is the layer of the system responsible for representing business data and logic.[Source: https://guides.rubyonrails.org/active_record_basics.html] Act...

weixin_26724741的博客 297

JFinal 源码分析 [DB+ActiveRecord]

我记得以前有人跟我说,“面试的时候要看spring的源码,要看ioc、aop的源码"那为什么要看这些开源框架的源码呢,其实很多人都是"应急式"的去读,就像读一篇文章一下,用最快的速度把文章从头到尾读一遍,那结果就是当你读完它,你也不清楚它讲了一个什么故事,想表达什么。 一个优秀的架构的源码我认为就好像一本名著一样,你的“文学”水平越高,你就越能读出作者设计的精妙之处。一篇源码在你不同水平的时候,...

weixin_34062469的博客 266

Rails详细介绍(七)ActiveRecord基础

     ActiveRecord是Rails提供的一个对象关系映射(ORM)层,从这篇开始,我们来了解Active Record的一些基础内容,连接数据库,映射表,访问数据等。        Active Record使用基本的ORM模式:表映射成类,行映射成为对象,列映射成对象的属性。     表和类     当你创建了一个ActiveRecord::Base类的子类,Active ...

Ruby爱好者 422

Rails中destroy_all和delete_all的差别

Rails删除一个Model对应的表的某些数据有delete_all和destory_all两种方法,本篇文章讲解一下两者的区别。

feigeswjtu的专栏 4669
上一篇: 看完几本Ruby、RoR书籍后的感受
下一篇: Rails源码研究之ActiveRecord:三,Transactions
hidetobj
博客等级 码龄19年 16粉丝 301原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值