Meta-Programming

Hi,

some month ago, I wanted to make a script, where you use different backgrounds for all scenes.

My first attempt was to write something like this:

Spoiler
module CONFIG SCENES = {Scene_Menu => "background1", Scene_Item => "background2"}endclass Scene_Menu alias create_background_old create_background def create_background if CONFIG::SCENES.include?(self.class) @background = Sprite.new @background.bitmap = Cache.menu(CONFIG::SCENES[self.class]) else create_background_old end endendclass Scene_Item alias create_background_old create_background def create_background if CONFIG::SCENES.include?(self.class) @background = Sprite.new @background.bitmap = Cache.menu(CONFIG::SCENES[self.class]) else create_background_old end endend#and so on
So like you see, it will be a bit difficult for a non-scripter, to add custom scenes without copy whole code parts and change scene_names.

I tried to solve this by iterate trough SCENE and apply changes only to the scenes included in the constant, but I failed, cause I didnt know how to do this.

Now, some month later, I have learned something about meta-programming.

This is how i could write it now:

Spoiler
module CONFIG SCENES = {Scene_Menu => "bg1", Scene_Item => "bg2"} #and so onendSCENE.each_key do | scene | next unless scene.ancestors.include? Scene_MenuBase scene.class_eval do def create_background @background_sprite = Sprite.new @background_sprite.bitmap = Cache.menu(CONFIG::SCENES[class.self]) end endend
My question now is, if it is ok to write code like that above or stick with the old code?
I don't see anything wrong with meta-programming.
"Meta-programming" is there for a reason. One of the best features of Ruby, honestly.

It's another tool in your toolbox. Use it appropriately and it will serve you well.

Original thread: https://forums.rpgmakerweb.com/threads/meta-programming.25339/