Skip to content
This repository was archived by the owner on Apr 18, 2018. It is now read-only.
This repository was archived by the owner on Apr 18, 2018. It is now read-only.

Use Virtus for defining attributes and helping with data-type coercions #36

@bmorton

Description

@bmorton

This isn't a bug, but I wanted to get some feedback on the viability of this being accepted if I open a PR for it. Basically, I want to replace the attribute definition stuff with Virtus: https://github.com/solnic/virtus

Virtus is an extraction from DataMapper that provides a common API for defining attributes and doing data-type coercion.

The cool thing here is that you don't have to define attributes with Virtus. This change would be completely backwards compatible with the current way of defining models. It would simply add the attribute DSL.

Here's what a model would look like using Virtus attributes:

class Note
  include Curator::Model

  attribute :id, String
  attribute :title, String
  attribute :description, String
  attribute :user_id, Integer
end

Basically, we'd let Virtus handle the constructor/mass assignment stuff and could remove the stuff in Curator for that. We can also define created_at/updated_at as Time types.

require 'curator'

module Curator
  module VirtusModel
    extend ActiveSupport::Concern

    included do
      include Virtus.model

      attribute :created_at, Time
      attribute :updated_at, Time

      attr_writer :version
    end

    def persisted?
      id.present?
    end

    def touch
      now = Time.now.utc
      created_at = now if created_at.nil?
      updated_at = now
    end

    def version
      @version || self.class.version
    end

    def ==(other)
      self.id == other.id
    end

    module ClassMethods
      include ActiveModel::Naming

      def current_version(number)
        @version = number
      end

      def version
        @version || 0
      end
    end
  end
end

Thoughts?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions