Jump to content
Tsukihime

Alias issues

Recommended Posts

How do I make sure that I don't run into exceptions due to aliasing methods that aren't defined?

 

class Game_Actor < Game_Battler
   alias :actor_setup :setup
   def setup(...)
      ...
   end
end

This works fine, but what if it's not a method that's provided in the default engine?

 

 

class Game_Actor < Game_Battler
   alias :actor_custom_method :custom_method
   def custom_method(...)
      ...
   end
end

Game_Actor#custom_method may be a custom method I define in one my of scripts, and then I'm aliasing it in OTHER scripts, but if people aren't using the first script that defines it, then the alias will fail.

Share this post


Link to post
Share on other sites

Usually at the beginning of scripts I put some code like this:

$imported = {} if $imported.nil?
$imported["YourScriptNameHere"] = true

 

Then in your other scripts, you can check if a certain script is installed and change the code accordingly. This can also help others make their scripts compatible with yours.

Share this post


Link to post
Share on other sites

That works, but the issue starts getting worse when you start having more and more scripts aliasing that particular method.

 

Like, if ORIGINAL_SCRIPT defined `custom_method`, then NEW_SCRIPT would check whether it exists, and alias if necessary. Otherwise, it would just proceed to define its own `custom_method`.

 

Now we have THIRD_SCRIPT, which will again alias `custom_method`, but now we need to check whether one of the two previous scripts were imported.

 

And then when I get to my 20th script, I'm checking whether one of the previous 20 scripts were imported.

Share this post


Link to post
Share on other sites

You can also simply check if a certain method has been defined.

In classes:

respond_to?(:method_name)
#you can optionally include a boolean as the second parameter
#if that second parameter is given and is true, private methods are also searched.

 

In modules:

method_defined?(:method_name)
#only searches public and protected methods
#you can also optionally use one of the following
public_method_defined?(:method_name)
private_method_defined?(:method_name)
protected_method_defined?(:method_name)

Share this post


Link to post
Share on other sites

Yeah, you should check for method definitions existing. Don't do this:

 

$imported = {} if $imported.nil?
$imported["YourScriptNameHere"] = true

 

If someone else doesn't include YourScriptNameHere (or anything in your script library) but does include some other person's script that happens to have the same method, you won't detect that or do an alias and end up overwriting their code.

Edited by Kaelan

Share this post


Link to post
Share on other sites
Guest
This topic is now closed to further replies.

  • Recently Browsing   0 members

    No registered users viewing this page.

×
Top ArrowTop Arrow Highlighted