Code Monkey home page Code Monkey logo

active_attr's Introduction

ActiveAttr

Build History Code Climate

ActiveAttr is a set of modules that makes it easy to create plain old Ruby models with functionality found in ORMs, like ActiveRecord, without reinventing the wheel. Think of ActiveAttr as the stuff ActiveModel left out.

ActiveAttr is distributed as a Ruby gem on rubygems.org.

ActiveAttr Railscast

Modules

Attributes

Including the Attributes module into your class gives you a DSL for defining the attributes of your model.

class Person
  include ActiveAttr::Attributes

  attribute :first_name
  attribute :last_name
end

person = Person.new
person.first_name = "Chris"
person.last_name = "Griego"
person.attributes #=> {"first_name"=>"Chris", "last_name"=>"Griego"}

AttributeDefaults

Including the AttributeDefaults module into your class builds on Attributes by allowing defaults to be declared with attributes.

class Person
  include ActiveAttr::AttributeDefaults

  attribute :first_name, :default => "John"
  attribute :last_name, :default => "Doe"
end

person = Person.new
person.first_name #=> "John"
person.last_name #=> "Doe"

QueryAttributes

Including the QueryAttributes module into your class builds on Attributes by providing instance methods for querying your attributes.

class Person
  include ActiveAttr::QueryAttributes

  attribute :first_name
  attribute :last_name
end

person = Person.new
person.first_name = "Chris"
person.first_name? #=> true
person.last_name? #=> false

TypecastedAttributes

Including the TypecastedAttributes module into your class builds on Attributes by providing type conversion for your attributes.

class Person
  include ActiveAttr::TypecastedAttributes
  attribute :age, :type => Integer
end

person = Person.new
person.age = "29"
person.age #=> 29

BasicModel

Including the BasicModel module into your class gives you the bare minimum required for your model to meet the ActiveModel API requirements.

class Person
  include ActiveAttr::BasicModel
end

Person.model_name.plural #=> "people"
person = Person.new
person.valid? #=> true
person.errors.full_messages #=> []

BlockInitialization

Including the BlockInitialization module into your class will yield the model instance to a block passed to when creating a new instance.

class Person
  include ActiveAttr::BlockInitialization
  attr_accessor :first_name, :last_name
end

person = Person.new do |p|
  p.first_name = "Chris"
  p.last_name = "Griego"
end

person.first_name #=> "Chris"
person.last_name #=> "Griego"

Logger

Including the Logger module into your class will give you access to a configurable logger in model classes and instances. Your preferred logger can be configured on an instance, subclass, class, parent class, and globally by setting ActiveAttr::Logger.logger. When using Rails, the Rails framework logger will be configured by default.

class Person
  include ActiveAttr::Logger
end

Person.logger = Logger.new(STDOUT)
Person.logger? #=> true
Person.logger.info "Logging an informational message"

person = Person.new
person.logger? #=> true
person.logger = Logger.new(STDERR)
person.logger.warn "Logging a warning message"

MassAssignment

Including the MassAssignment module into your class gives you methods for bulk initializing and updating the attributes of your model. Any unknown attributes are silently ignored.

class Person
  include ActiveAttr::MassAssignment
  attr_accessor :first_name, :last_name, :age
end

person = Person.new(:first_name => "Christopher", :last_name => "Griego")
person.attributes = { :first_name => "Chris", :age => 21 }
person.first_name #=> "Chris"
person.last_name #=> "Griego"

MassAssignment supports mass assignment security/sanitization if a sanitizer is included in the model. If using Rails 4.0, include ActiveModel's forbidden attributes protection module to get support for strong parameters.

class Person
  include ActiveAttr::MassAssignment
  include ActiveModel::ForbiddenAttributesProtection
  attr_accessor :first_name, :last_name
end

person = Person.new(ActionController::Parameters.new({
  :first_name => "Chris",
  :last_name => "Griego",
}).permit(:first_name))
person.first_name #=> "Chris"
person.last_name #=> nil

If using Rails 3.x or the Protected Attributes gem, include ActiveModel's mass assignment security module to get support for protected attributes, including support for mass assignment roles.

class Person
  include ActiveAttr::MassAssignment
  include ActiveModel::MassAssignmentSecurity
  attr_accessor :first_name, :last_name
  attr_protected :last_name
end

person = Person.new(:first_name => "Chris", :last_name => "Griego")
person.first_name #=> "Chris"
person.last_name #=> nil

If using the Strong Parameters gem with Rails 3.2, include the forbidden attributes protection module after including the mass assignment security module.

class Person
  include ActiveAttr::MassAssignment
  include ActiveModel::MassAssignmentSecurity
  include ActiveModel::ForbiddenAttributesProtection
end

Serialization

The Serialization module is a shortcut for incorporating ActiveModel's serialization functionality into your model with one include.

class Person
  include ActiveAttr::Serialization
end

Model

The Model module is a shortcut for incorporating the most common model functionality into your model with one include. All of the above modules are included when you include Model.

class Person
  include ActiveAttr::Model
end

Integrations

Ruby on Rails

When using ActiveAttr inside a Rails application, ActiveAttr will configure your models' default logger to use the Rails logger automatically. Just include ActiveAttr in your Gemfile.

gem "active_attr"

RSpec

ActiveAttr comes with matchers and RSpec integration to assist you in testing your models. The matchers also work with compatible frameworks like Shoulda.

require "active_attr/rspec"

describe Person do
  it do
    should have_attribute(:first_name).
      of_type(String).
      with_default_value_of("John")
  end
end

active_attr's People

Contributors

andrykonchin avatar artinboghosian avatar bpoweski avatar cgriego avatar cwest avatar eregon avatar geoffharcourt avatar gogainda avatar goganchic avatar jackal998 avatar jbhannah avatar kbaba1001 avatar koic avatar laserlemon avatar matthodan avatar mindreframer avatar msaffitz avatar rmm5t avatar robin850 avatar sparksp avatar steveh avatar subvertallchris avatar vfonic avatar wonda-tea-coffee 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

active_attr's Issues

Attributes

Including Attributes gets you attribute definition with .attribute (no typecasting) with #{attr}, #{attr}=, #read_attribute, #write_attribute, and #attributes that utilize an internal @attributes instance variable.

Time Zone Conversion

Similar to type casting, but it's conversion of the data instead of the type. For example, normalize Time/DateTime to UTC. Related is stripping fractional seconds.

StrictMassAssignment

This module will raise an exception when mass assigning attributes that include an unknown attribute.

Dynamic Attributes

Makes a model schemaless model to allow undefined attributes to be written and read, similar to a struct.

QueryAttributes

Defines #{attr}? and #attribute?

The behavior of these methods will be affected by Typecasting.

Typecasting flyweight

Give the large amount of typecasting that could occur, it would be useful for the framework to cache the results of the conversion for types.

  1. opt in
  2. lifecycle methods to purge the cached conversions
  3. block form to disable the action
  4. block form to enable the action

Build on Travis

Add travis config, hook, and a README.md with SSL build image.

AttributeDefaults

Allow defaults to be defined for attributes. Support procs for lazy evaluation. Should be applied at initialization.

Logger

Class and instance logger accessors, default to Rails Logger.

Attributes.attribute_names

ActionPack will try to determine the attributes a model has by accessing the class method .attribute_names. One use case is in ParamsWrapper. ActiveRecord returns an Array of Strings.

MassAssignment

Including MassAssignment should get you an #initialize(attributes) method and an #attributes= method that walks a hash and assigns values if the object responds to a setter for the key.

Initialization methods do not chain

This means that right now you can't mix MassAssignment and Attributes together and both work.

  1. I tried just calling super, and that works great in 1.9 but fails in 1.8 because Object#initialize in 1.8 doesn't accept any arguments while 1.9 will accept any number of arguments. 1.8 fails with ArgumentError.
  2. I tried using alias method chaining, but as soon as the class defines its own #initialize then it overwrites the carefully chained initialization methods.
  3. I tried and considered other things as well…
  4. I think the best shot is to do alias method chaining inside of an anonymous Module similar to how ActiveModel::AttributeMethods works.

MultiParameterAttributes

Handle ActionPack's multi-parameter params for complex attributes that come from date fields and such.

MassAssignmentSecurity

Use ActiveModel::MassAssignmentSecurity, with its roles support, hooked into the MassAssignment methods.

InitializationCallback

I debate the usefulness of this, but a module that provides an after_initialize callback will provide parity with ORMs and make it easier to hook into initialization for novice Ruby coders.

Model

An mostly all-in-one starting point, comes with what most people would expect to be built-in.

Replace StrictMassAssignment with injectable behavior

Instead of StrictMassAssignment being a module, change MassAssignment to use injectable behavior for dealing with unknown attributes. Allow a default behavior to be set on the class (overridden on subclasses and a global default on the module) and use options to override the behavior at call time.

Typecasting

Offer typecasting by attribute. @attributes should stay in the raw form. Method for getting the attribute value from before typecasting should be available. Probably need to define #read_attribute_for_validation that reads the before typecast value.

.attribute(:attr_name, :type => Class)

NestedAttributes

Actionpack's FormHelper depends on particular methods being present to work with nested/association attributes.

Yardoc

Setup and backfill documentation using yard.

Rename Model to BasicModel

Model will be reserved for a full-featured model while BasicModel is just the bare minimum to pass ActiveModel's lint.

MassAssignmentSecurity

Use ActiveModel::MassAssignmentSecurity, with its roles support, hooked into the MassAssignment methods.

Model

The bare bones required to pass ActiveModel's lint tests.

Associations

Models have associations with other models, and attributes don't cover this case very well (especially when initializing a model with a deeply nested hash).

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.