Gem rom 是个新的数据访问 gem

chenge · 2015年04月30日 · 最后由 lgn21st 回复于 2015年05月01日 · 1958 次阅读

rom 是个新东西,感觉比 AR 要难学一些。不过可以直接在内存里,这对测试应该很有帮助吧。有没有熟悉的网友介绍一下用法。

require 'rom'
ROM.setup(:memory)

# This is our domain-specific class
class User
  attr_reader :name, :age

  def initialize(attributes)
    @name, @age = attributes.values_at(:name, :age)
  end
end

# Here we define user relation which encapsulates accessing user data that
# we can map to domain objects
class Users < ROM::Relation[:memory]
  def by_name(name)
    restrict(name: name)
  end

  def adults
    restrict { |user| user[:age] >= 18 }
  end
end

# Even though mappers can be derived from model definitions here's how you
# could define it explicitly
class UserMapper < ROM::Mapper
  relation :users
  register_as :entity

  model User

  attribute :name
  attribute :age
end

# You can define specialized commands that handle creating, updating and deleting
# data, those classes can use external input param handlers and validators too
class CreateUser < ROM::Commands::Create[:memory]
  register_as :create
  relation :users
  result :one
end

# finalize the setup and retrieve object registry (aka ROM env)
rom = ROM.finalize.env

# accessing defined commands
rom.command(:users).create.call(name: "Joe", age: 17)
rom.command(:users).create.call(name: "Jane", age: 18)

# reading relations using defined mappers
puts rom.relation(:users) { |r| r.adults }.as(:entity).to_a.inspect
# => [#<User:0x007fdba161cc48 @id=2, @name="Jane", @age=18>]

http://rom-rb.org/introduction/

看了一下介绍说仍然处于实验性质的工具,设计思想是在不同类型数据库上建立一层抽象,达到简化的目的,不知道作者是不是嫌弃 ActiveRecord 或者 MongoID 这些东西太复杂了,所以才重新造个轮子。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号