Robert Klemme
2/16/2008 12:28:00 PM
On 16.02.2008 08:48, Brad Ottoson wrote:
> I'm working on an application for generating code skeletons from xml
> template files and have run into a snag. I'm trying to organize a set
> of code in a directory and inside that use modules. I have a set of
> files in a subdirectory of my project directory called lang_cpp. I'll
> paste in some code to show what I'm trying.
>
> --method_constructor.rb(in lang_cpp directory):
>
> module XTECpp::MethodConstructor
> def getDeclaration(codeClass)
> return " " + codeClass.name + "();\n"
> end
> end
>
> --method_destructor.rb(in lang_cpp directory):
> module XTECpp::MethodDestructor
> def getDeclaration(codeClass)
> return " ~" + codeClass.name + "();\n"
> end
> end
>
> Later in some other code I include the files using:
> require 'lang_cpp/method_constructor.rb'
> require 'lang_cpp/method_destructor.rb'
>
> which seems to work fine. Later on I try the following:
> case funItem.name
> when "empty_constructor"
> headerString <<
> XTECpp::MethodConstructor::getDeclaration(codeClass)
> when "empty_destructor"
> headerString <<
> XTECpp::MethodDestructor::getDeclaration(codeClass)
> when "operator_equality_assignment"
> headerString <<
> XTECpp::MethodEqualityAssign::getDeclaration(codeClass)
> when "readugp"
> headerString <<
> XTECpp::MethodReadUGP::getDeclaration(codeClass)
> end
>
> and when I run it I get the error:
>
> C:\code\Ruby\XMLTemplateEngine\lib/lang_cpp/method_constructor.rb:5:
> uninitialized constant XTECpp (NameError)
> from C:\code\Ruby\XMLTemplateEngine\lib/lang_cpp.rb:6:in `require'
> from C:\code\Ruby\XMLTemplateEngine\lib/lang_cpp.rb:6
> from C:/code/Ruby/XMLTemplateEngine/lib/main.rb:6:in `require'
> from C:/code/Ruby/XMLTemplateEngine/lib/main.rb:6
>
> I tried changing the module names to the form XTECpp_MethodConstructor
> so each function was in it's own unique module but I got errors doing
> that too. I'm not sure if you can ever do things this way in Ruby but
> I'd like to since this organization appeals to me.
You want to use modules as namespaces but actually you define instance
methods in modules. A small change will provide what you want:
module XTECpp::MethodConstructor
def self.getDeclaration(codeClass)
return " " + codeClass.name + "();\n"
end
end
A few other remarks: if you have just one method per module then the
idea with namespaces does not really make sense.
You use camelCase for method names while in Ruby code this_style is
conventionally used.
Your methods return leading whitespace which I assume serves to do some
indentation (and also a trailing linefeed). I would not do that but let
the invoking code make sure indentation is properly - otherwise you
limit yourself to a single level of indentation. Also modularity of
your code suffers because now your getXXX methods return a piece of code
*and* do indentation.
Kind regards
robert