MetaProgramming Chapter 1

MetaProgramming Chapter 1

Ruby 元编程 第一章

该文档包含Ruby元编程含义的基本概述。

阅读文档,你将学到:

  • 元编程是什么

Ghost Towns and Marketplaces

  1. Ruby 与C++ 的区别
    • 运行时,变量与方法可见, 且可以创建
      自省|内省(introspection): 对象在运行时可以调用自身的方法,询问详细信息。
Class Greeting
  def initialize(text)
    @text = text
  end

  def welcome
    @text
  end
end
  my_object = Greeting.new('hello')

  my_object.class  # => Greeting 所属类
  my_object.class.instance_methods(false)   # => [:welcome] 类的实例方法,不包括继承方法
  my_object.instance_variables              # => [:@text] 对象的实例变量

ActiveRecord::Base

NOTE: 将数据库中的表与类进行映射,每条记录与对象进行映射

当创建一个对象|访问对象属性时,对象将与数据库交互。这种交互功能已被封装在ActiveRecord::Base类中

class Entity
  attr_reader :table, :ident

  def initialize(table, ident)
    @table = table
    @ident = ident
    Database.sql "INSERT INTO #{@table} (id) VALUES (#{@ident})"
  end

  def set(col, val)
    Database.sql "UPDATE #{@table} SET #{col}='#{val}' WHERE id=#{@ident}"
  end

  def get(col)
    Database.sql ("SELECT #{col} FROM #{@table} WHERE id=#{@ident}")[0][0]
  end
end
class Movie < Entity
  def initialize(ident)
    super "movies", ident
  end

  def title
    get "title"
  end

  def title=(value)
    set "title", value
  end

  def director
    get "director"
  end

  def director=(value)
    set "director", value
  end
end

Movies表创建记录:

  movie = Movie.create
  movie.title = "Doctor Strangelove"
  movie.title # => "Doctor Strangelove"

WARNING: 重复代码太多,定义了@title成员,方法title、title=, title字符串常量

使用ActiveRecord 类库优化Movie类

class Movie < ActiveRecord::Base
end

Movies表创建记录:

  movie = Movie.create
  movie.title = "Doctor Strangelove"
  movie.title # => "Doctor Strangelove"

NOTE: ActiveRecord在运行是读取数据库表模式,找到类的相应字段,然后自动定义两个同名属性和相应的访问器。
即:ActiveRecord 在程序运行时动态创建了Movie#tilte 和 Movie#director=方法

元编程是什么?

NOTE: 元编程是编写能在运行时操作语言构件的代码
Metaprogramming is writing code that manipulates language constructs at
runtime.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值