Question

I'm quite new in RoR and right now I'm facing a problem. I'm implementing an Attendance system and I have Event resource in the application. What I want to do is the possibility to call event.color (on an instance of Event) and get back classic css color string (like #2EAC6A). I don't want to create new column or table in the database if it's possible. That means that it would be best if this color variable is handled by ruby itself.

I want to set the color of event after it's creation dependant on it's type. What I was thinking of is something like this to set the color:

class Event < ActiveRecord::Base
  after_create :set_color
  ...

  def set_color
    case self.type
    when type1
      #Here I want to set the color for event of type1
    when type2
      #Here I want to set the color for event of type2
    when ....
    .
    .
    end
 end

This is just for setting the color (and still I'm not sure it's functional...) but I have no idea how to keep color variable for each event without the database and how to make Event.color method call possible. I'm using RoR v 3.2.14

Please, I would be glad for any help. Thank you and have a nice day!

J.S.

Was it helpful?

Solution

If your colors never change - or every type1 always has the same color as another type1 you could use different CONSTANTS in your model or a bitmask.

example for using constants:

class Event < ActiveRecord::Base

  COLOR_TYPE1 = "#2EAC6A"
  COLOR_TYPE2 = "#000000"
  COLOR_TYPE3 = "#ffffff"

  def color
    case self.type
    when type1
      COLOR_TYPE1
    when type2
      COLOR_TYPE2
    when type3
      COLOR_TYPE3
    else
     raise "for this type is no color defined!"
    end
  end

end

You won´t need to set the color - because you do not have an attribute color. Simple use a normal method which returns the correct color for an instance, dependent on the type of the instance.

Another option without constants: (this approach is better than the above one, in my opinion :-) )

class Event < ActiveRecord::Base

  def color
    case self.type
    when type1
      "#2EAC6A"
    when type2
      "#000000"
    when type3
      "#ffffff"
    else
     raise "for this type is no color defined!"
    end
  end

end

If you have different classes for each instance, you must not use the constants, you just can define the colors directly:

class Type1 < Event
  def color
    "#2EAC6A"
  end
end

def Type2 < Event
 def color
   "#000000"
 end
end

def Type3 < Event
  def color
    "#ffffff"
  end
end

Different classes have the advantage, that you can handle all your stuff which depends on the type directly in a subclass of your parent class "Event". Do you get the idea?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top