Class: Ward::Context

Inherits:
Object
  • Object
show all
Defined in:
lib/ward/context.rb

Overview

A class which represents “somewhere” from which a value can be retrieved for validation.

A context initialized with a :length attribute assumes that the value for validation can be retrieved by calling length on the target object.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attribute, *context_args, &context_block) ⇒ Context

Creates a new validator instance.

Parameters:

  • attribute (#to_sym)

    The name of the attribute to be validated.

  • *context_args (*)

    Arguments to be used when calling the context.

  • context_block (Block)

    A block to be used when calling the context.



40
41
42
43
44
45
46
# File 'lib/ward/context.rb', line 40

def initialize(attribute, *context_args, &context_block)
  @attribute = attribute.to_sym
  @context_args, @context_block = context_args, context_block

  @natural_name =
    ActiveSupport::Inflector.humanize(@attribute.to_s).downcase
end

Instance Attribute Details

#attributeSymbol (readonly)

Returns the name of the attribute to be validated.

Returns:

  • (Symbol)


14
15
16
# File 'lib/ward/context.rb', line 14

def attribute
  @attribute
end

#natural_nameString (readonly)

Returns the ‘natural name’ of the attribute.

This name is used when generating error messages, since you probably don’t want you end users to be presented with (occasionally) obscure attribute names.

Examples:

:name     # => Name
:a_field  # => A field
:post_id  # => Post

Returns:

  • (String)


29
30
31
# File 'lib/ward/context.rb', line 29

def natural_name
  @natural_name
end

Instance Method Details

#value(target) ⇒ Object

Returns the value of the context for the given target object.

Examples:


Context.new(:length).value('abc')
# => 3

Context.new(:length_as_string) do |target|
  target.length.to_s
end.value('abc')
# => '3'

Parameters:

  • target (Object)

    The object from which the value is to be retrieved.

Returns:

  • (Object)


65
66
67
# File 'lib/ward/context.rb', line 65

def value(target)
  target.__send__(@attribute, *@context_args, &@context_block)
end