Is it ok to use struct as constants in initializer?

I want to define simple global objects that contain a code and description for custom errors. Is it a bad idea to use structs in an initializer in the app?

api_error_constants.rb in /config/initializers

error_type = Struct.new(:code, :description) BAD_JSON = error_type.new("001" , "Problem parsing JSON") BAD_XML = error_type.new("002" , "Problem parsing XML") ... ...

Or is there a more appropriate/standard way?

class MyClass   class APIParseError < StandardError     def initialize(code, lib)       @code = code       @lib = lib     end

    def to_s       "#{@code}: Problem parsing #{@lib}"     end   end end

raise(MyClass::APIParseError.new("001", :XML)) #=> MyClass::MyError: 001: Problem parsing XML

This would actually display: "MyClass::APIParseError" I had a misspelling since I didn't run it through an REPL to get the output I just wrote it so of course typos can happen but it will show you the right error class when you output it.

Jordon Bedwell wrote in post #1087053:

error_type = Struct.new(:code, :description) BAD_JSON = error_type.new("001" , "Problem parsing JSON") BAD_XML = error_type.new("002" , "Problem parsing XML")

class MyClass   class APIParseError < StandardError     def initialize(code, lib)       @code = code       @lib = lib     end

    def to_s       "#{@code}: Problem parsing #{@lib}"     end   end end

raise(MyClass::APIParseError.new("001", :XML)) #=> MyClass::MyError: 001: Problem parsing XML

Thanks Jordon. I wanted to keep my question simple but maybe it needed more details. Sorry I have to paste a bunch of code...

I need to respond with the api using json:

{   "result": {"created":"0","failed":"0"},   "errors":[     {"error":{"message":"Problem parsing JSON","code":"001"}}   ] }

I use Rabl to generate the json I give back. Rabl works well with openStruct. There can be several errors to be reported.

Ok, I would remove my previous post if I could but I can't access it anymore.

In any case. I have improved that code to a better version where I rely on raise and rescues to handle exceptions generated by the module. No more ugly if xxxx != false

Anyway my question was not about how to generate exceptions but about the fact of using a struc in my initializers.

I would delete the whole thread anyway...

This is a mailing list not a forum (though you may be accessing via a forum like interface). Emails cannot be deleted by the sender. Once it is on my machine only I can delete it (I hope, otherwise I am in trouble).

Colin