Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Virtus

 Virtus

Florian Gilcher

October 10, 2013
Tweet

More Decks by Florian Gilcher

Other Decks in Programming

Transcript

  1. URM

  2. This is a partial extraction of the DataMapper Property API

    with various modifications and im- provements. The goal is to provide a common API for defining attributes on a model...
  3. class User include Virtus.model attribute :name, String attribute :age, Integer

    attribute :birthday, Date attribute :registered, Time, :default =>->() { Time.now } end
  4. json = '{"name": "Florian Gilcher", "age": 30, "birthday": "October 4th,

    1983"}' parsed = JSON.parse(json) user = User.new(parsed) #=> #<User:0x000001008d8b68 @age=30, @birthday= #<DateTime: 1983-10-04T...>, @name="Florian Gilcher", @registered="....">
  5. module Named include Virtus.module attribute :name, String end class User

    include Named end u = User.new u.attributes = {:name => "Florian Gilcher"}
  6. class Location include Virtus.value_object values do attribute :lat, BigDecimal attribute

    :lon, BigDecimal end end Location.new(:lat => 1, :lon => 1) == Location.new(:lat => 1, :lon => 1)
  7. class User include Virtus.model( :constructor => false, :mass_assignment => false

    ) attribute :name, String attribute :age, Integer attribute :birthday, DateTime end
  8. class User include Virtus.model(:coerce => false) attribute :name, String attribute

    :age, Integer attribute :birthday, DateTime end u = User.new u.age = "123" u.age #=> "123"
  9. class ShowOff attribute :users, Set[User] attribute :tags, Array[String] attribute :meta,

    Hash[Symbol => String], :coerce => false attribute :i_dont_know_what_this_is_good_for, Hash[String => Hash[String => User]] end
  10. class Preferences include Virtus.model attribute :columns, Fixnum, :default => 2

    attribute :scheme, String end class User < ActiveRecord::Base serialize :preferences, Preferences end
  11. pref = Preferences.new(:columns => 2, :scheme => "dark") User.create(:name =>

    "fgilcher", :preferences => pref) User.first #=> #<User id: 1, name: "fgilcher", preferences: #<Preferences...>>
  12. Virtus comes at a small cost, so it should be

    used for domain models only.