Code Monkey home page Code Monkey logo

validated_object's Introduction

Gem Version Code Climate

ValidatedObject

Plain Old Ruby + Rails Validations = self-checking Ruby objects. Here's a quick example of a common case: an immutable, required, type-checked attribute:

class Person < ValidatedObject::Base
  validated_attr :name, type: String, presence: true
end

# Using it
me = Person.new(name: 'Robb')

I use classes like these as Data Transfer Objects at my system boundaries.

Goals

  • Very readable error messages
  • Clean, minimal syntax

This is a small layer around ActiveModel::Validations. (About 25 lines of code.) So if you know how to use Rails Validations, you're good to go. I wrote this to help with CSV data imports and website structured data.

Usage

Writing a self-validating object

All of the ActiveModel::Validations are available, plus a new one, TypeValidator.

class Dog < ValidatedObject::Base
  # Plain old Ruby
  attr_accessor :name, :birthday

  # Plain old Rails
  validates :name, presence: true
  
  # A new type-validation if you'd like to use it
  validates :birthday, type: Date, allow_nil: true  # Strongly typed but optional
end

We can make it immutable with attr_reader:

class ImmutableDog < ValidatedObject::Base
  attr_reader :name, :birthday

  validates :name, presence: true
  validates :birthday, type: Date, allow_nil: true
end

attr_reader followed by validates is such a common pattern that there's a second DSL which wraps them up into one call: validates_attr.

Here's the immutable version of Dog re-written with the simplified DSL:

class ImmutableDog < ValidatedObject::Base
  validates_attr :name, presence: true
  validates_attr :birthday, type: Date, allow_nil: true 
end

About that type: check

The included TypeValidator is what enables type: Date, above. All classes can be checked, as well as a pseudo-class Boolean. E.g.:

#...
validates :premium_membership, type: Boolean
#...

Instantiating and automatically validating

# This Dog instance validates itself at the end of instantiation.
spot = Dog.new(name: 'Spot')
# We can also explicitly test for validity because all of
# ActiveModel::Validations is available.
spot.valid?  # => true

spot.birthday = Date.new(2015, 1, 23)
spot.valid?  # => true

Good error messages

Any of the standard Validations methods can be used to test an instance, plus the custom check_validations! convenience method:

spot.birthday = '2015-01-23'
spot.valid?  # => false
spot.check_validations!  # => ArgumentError: Birthday is a String, not a Date

Note the clear, explicit error message. These are great when reading a log file following a data import. It describes all the invalid conditions. Let's test it by making another attribute invalid:

spot.name = nil
spot.check_validations!  # => ArgumentError: Name can't be blank; Birthday is a String, not a Date

Use in parsing data

I often use a validated object in a loop to import data, e.g.:

# Import a CSV file of dogs
dogs = []
csv.next_row do |row|
  begin
    dogs << Dog.new(name: row.name)
  rescue ArgumentError => e
    logger.warn(e)
  end
end

The result is that dogs is an array of guaranteed valid Dog objects. And the error log lists unparseable rows with good info for tracking down problems in the data.

Use in code generation

My Schema.org structured data gem uses ValidatedObjects to recursively create well formed HTML / JSON-LD.

Installation

Add this line to your application's Gemfile:

gem 'validated_object'

And then execute:

$ bundle

Or install it yourself as:

$ gem install validated_object

Development

(TODO: Verify these instructions.) After checking out the repo, run bin/setup to install dependencies. Then, run rake spec to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.

Contributing

Bug reports and pull requests are welcome on GitHub.

License

The gem is available as open source under the terms of the MIT License.

validated_object's People

Contributors

dogweather avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

validated_object's Issues

Idea: make attr_accessor or validates optional

I'd like to DRY up this code:

class Dog < ValidatedObject::Base
  attr_accessor :weight, :neutered

  validates :weight, type: Numeric
  validates :neutered, type: Boolean
end

So maybe somehow implement an implicit attr_accessor call:

class Dog < ValidatedObject::Base
  validates :weight, type: Numeric
  validates :neutered, type: Boolean
end

Or alternatively, override attr_accessor to delegate to validates if options are specified:

class Dog < ValidatedObject::Base
  attr_accessor :weight, type: Numeric
  attr_accessor :neutered, type: Boolean
end

attr_reader compatibility

The code currently requires attr_accessor. But I'd like the ability to make my attributes read-only.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.