Class: Cardlike::Card

Inherits:
Object
  • Object
show all
Defined in:
lib/cardlike/card.rb

Overview

Represents a game card. Best used with the Card and Deck DSL. See Cardlike.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Card

Create an instance of a Card. Arguments are a hash that should include :name at a minimum. Perhaps a better idea is to use Card.create or Cardlike.card. Also see Cardlike.type_of_card.



14
15
16
17
18
# File 'lib/cardlike/card.rb', line 14

def initialize(options={})
  self.name = options[:name]
  @card_type = options[:card_type] || nil
  @properties = {}
end

Instance Attribute Details

#card_typeObject

Returns the value of attribute card_type.



7
8
9
# File 'lib/cardlike/card.rb', line 7

def card_type
  @card_type
end

#nameObject

Returns the value of attribute name.



5
6
7
# File 'lib/cardlike/card.rb', line 5

def name
  @name
end

Class Method Details

.create(name, &block) ⇒ Object

Factory method to create an instance of a Card. This sets the name of the card and its properties using the Card DSL in the corresponding block. You can also use Cardlike.card, which does the same thing. Probably more useful is to create custom card types using Cardlike.type_of_card and create them using the new_ methods.

Card.create "Big Monster"

Preferred over Card.new.



36
37
38
39
40
# File 'lib/cardlike/card.rb', line 36

def self.create(name, &block)
  c = self.new(name: name)
  c.instance_eval(&block) if block_given?
  c
end

.has(prop) ⇒ Object

Class DSL method for setting custom properties for a Card. See Cardlike.type_of_card.



64
65
66
# File 'lib/cardlike/card.rb', line 64

def self.has(prop)
  define_method(prop, lambda { |arg=nil| return @properties[prop] unless arg; raise "Cards are immutable." if @properties.has_key? prop; @properties[prop] = arg })
end

.has_block(prop) ⇒ Object

Class DSL method for setting custom properties for a Card that include a block. See Cardlike.type_of_card.



56
57
58
# File 'lib/cardlike/card.rb', line 56

def self.has_block(prop)
  define_method(prop, lambda { |&block| return @properties[prop] unless block; raise "Cards are immutable." if @properties.has_key? prop; @properties[prop] = block })
end

Instance Method Details

#[](prop) ⇒ Object

Return custom properties of this Card. Custom properties can be set using the Card.has method, ideally inside a Cardlike.type_of_card block.

@king_of_diamonds[:suit] # => 'Diamonds'


48
49
50
# File 'lib/cardlike/card.rb', line 48

def [](prop)
  @properties[prop]
end

#to_sObject



68
69
70
71
72
73
# File 'lib/cardlike/card.rb', line 68

def to_s
  t = []
  t << "Name: #{name}"
  @properties.each { |p,v| t << "#{p}: #{v}" unless v.nil? or v.is_a? Proc } 
  "[ "+t.join("; ")+" ]"
end