# Newbie: Make this code better?

**URL:** <https://www.ruby-forum.com/t/newbie-make-this-code-better/90245>\
**Category:** Ruby\
**Created:** [March 27, 2007, 1:26am UTC](https://www.ruby-forum.com/t/newbie-make-this-code-better/90245 "2007-03-27T01:26:07Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![josh](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/45deac/32.png) [@josh](https://www.ruby-forum.com/u/josh)\
**Post date:** [March 27, 2007, 1:26am UTC](https://www.ruby-forum.com/t/newbie-make-this-code-better/90245/1 "2007-03-27T01:26:07Z")

</div>

Hi all

Another newbie question. I have the following code:

private  
def model\_obj\_name  
CountriesController.controller\_class\_name.underscore.sub(/\_controller$/,  
‘’).singularize  
end

I use it quite a lot, and it’s always the same, so I’d like to be  
executed only once and then stored somewhere and every following time it  
just returns this value.

I thought about putting this stuff into the initialize body and creating  
an attr\_accessor, but then it would be public, right? But I need it  
private…

Any cool solution? Thanks 🙂  
Josh

---

<div class="post-metadata">

**Author:** ![josh](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/45deac/32.png) [@josh](https://www.ruby-forum.com/u/josh)\
**Post date:** [March 27, 2007, 1:33am UTC](https://www.ruby-forum.com/t/newbie-make-this-code-better/90245/2 "2007-03-27T01:33:23Z")

</div>

hmmm, class or instance variable / cached function?

Have you looked at [http://rubymentor.rubyforge.org](http://rubymentor.rubyforge.org) ?

Aur

---

<div class="post-metadata">

**Author:** ![josh](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/45deac/32.png) [@josh](https://www.ruby-forum.com/u/josh)\
**Post date:** [March 27, 2007, 1:35am UTC](https://www.ruby-forum.com/t/newbie-make-this-code-better/90245/3 "2007-03-27T01:35:23Z")

</div>

Joshua M. wrote:

> I use it quite a lot, and it’s always the same, so I’d like to be

What about this?

private  
def model\_obj\_name  
@name ||=  
CountriesController.controller\_class\_name.underscore.sub(/\_controller$/,  
‘’).singularize  
end

---

<div class="post-metadata">

**Author:** ![josh](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/45deac/32.png) [@josh](https://www.ruby-forum.com/u/josh)\
**Post date:** [March 27, 2007, 4:28am UTC](https://www.ruby-forum.com/t/newbie-make-this-code-better/90245/4 "2007-03-27T04:28:35Z")

</div>

What’s wrong with using CountriesController#controller\_name?

> **[ActionController::Base](https://api.rubyonrails.org/classes/ActionController/Base.html#M000256)**
>
> Action Controllers are the core of a web request in Rails. They are made up of one or more actions that are executed on request and then either it renders a template or redirects to another action.

Converts the class name from something like  
“OneModule::TwoModule::NeatController” to “neat”.
