How to use #selector? to call another method - xcode

I'm trying to call a method inside my viewDidLoad method. How can I do that? I did a fast search and I found #selector. I have never used it before, can any one give me a fast example.

You don't necessarily need selector to call a method, you can invoke it directly, e.g. to call someMethod method that takes no parameters on someObject you can do the following:
[anObject someMethod];
or to call someMethod on current object you can use self:
[self someMethod];
If you really need to call a method via selector use performSelector: method (or another of few methods of 'performSelector' family) of NSObject:
[anObject performSelector:#selector(someMethod)];

Related

Is there a way to store an instance method inside a variable without running that function first? In Ruby

I am trying to store an instance method as a variable so I can pass it into a way to store logic on a menu I am building.
For example, I want my our_startup.prompt method to be stored in my start_game_ui.logic array. I am trying to do this using a start_game_ui.set_logic function which shovels arguments into the logic array. I would like to shovel 6 methods into the logic array so that when I run my final function to puts and receive input 1 - 6. If the user chooses 1 it should run the function in the first element of the array.
our_startup = Startup.new("No Name")
## START GAME UI ##
start_game_ui = UI.new("start_game_ui")
start_game_ui.menu_items = ["[1] - Yes", "[2] - Generate Another"]
##set up logic##
method1_test = our_startup.set_name("test")
rerun = start_game_ui.prompt
start_game_ui.set_logic(method1_test, rerun)
When I run this, my start_game_ui.prompt method will run. I want to store the start_game_ui.prompt method in that variable rerun without having the method run.
Once I run my final method and choose 1 it should return "test". However when I run this it runs start_game_ui.prompt and I don't want it to.
I hope you can understand what I mean. I have 2 classes UI and Startup if you couldn't already tell.
PLEASE DO NOT TELL ME I CAN DO method(:something) this does not help as it is an instance method being called by another instance. Unless you can tell me how to get that symbol to correspond with the correct method inside the instance. I've tried method(our_startup.prompt) and it does not work.
PLEASE DO NOT TELL ME I CAN DO method(:something) this does not help as it is an instance method being called by another instance.
I would really like to not tell you that, but unfortunately, that is the correct answer:
rerun = start_game_ui.method(:prompt)
# Then, later when you need to call it:
result = rerun.()
Not using Object#method, as you require in your question, leads to significant added complexity, e.g. by passing around the receiver and the name of the method separately:
rerun_receiver_and_message = [start_game_ui, :prompt]
# Then, later when you need to call it:
result = rerun_receiver_and_message.first.public_send(rerun_receiver_and_message.last)
The only thing you can store in variables and pass as arguments are objects.
Procs and Lambdas are objects, so you should be able to do something like
rerun = -> {start_game_ui.prompt}
start_game_ui.set_logic(method1_test, rerun)
rerun is storing the call to the method, not the results of the method
At the point where you need to execute the method, you would do
rerun.call
Note that Procs and Lambdas can also specify arguments, that you can supply at the time of the call.
I'm not sure if this helps with your problem, but hope it does.
If you'd like to get the instance method from inside the instance of your object, then you can use this: our_startup.method(:prompt)
I don't really understand what your end goal is, so I'm going to suggest you read up a little further on Ruby's object model and methods and provide you some guidance instead.
The method method returns an instance of Method (an object). If this is confusing, read it more slowly and check out the Method documentation. Whether the method being referenced by the argument is an instance method or not is irrelevant to the behavior of the method method.
Directly addressing something you said in the question: using method(:foo) does not call the referenced method (e.g. foo).
You can unbind a method from the source receiver (creating an UnboundMethod that can't be called) and rebind it to another receiver if you need to:
my_method_instance = some_string.method(:to_s)
# Now I can call `some_string.to_s` like so:
my_method_instance.to_s
# This isn't very useful for `to_s`, but it could be in other situations
method_instance = SomeModule::SomeHelper.method(:parse_html)
array_of_html_docs = array_of_strings.map(&method_instance)
# And you can unbind the method from the original receiver:
my_unbound_method_instance = my_method_instance.unbind
# And rebind it elsewhere
my_unbound_method_instance.bind(some_other_receiver)
my_unbound_method_instance.call(args) # receiver is `some_other_receiver` here

Ruby rspec mocking a utility method

How does one mock a utility method that is located in a file referenced by
require 'myfile.rb'
The contents of the file are like so.
public
def my_method_name(arg1, arg2, arg3)
{
....
}
At the moment, I have something like:
double("mydouble", "my_method_name" => somehash)
I then unit test the class I am testing, which calls this method, but this does not seem to be mocking the method at all.
All help is appreciated
Basically, the method I want to mock does some network query. I want to just say: Anytime this method is called, return this hash. This method is not part of a class (or so I believe).
In Ruby all methods are associated to something (module or class). Methods that you define at the top level actually become private methods of Kernel.
x = double("mydouble", "my_method_name" => somehash)
Doesn't stub the method my_method_name. It creates a double (separate object). If you invoke #my_method_name on it, it will respond with somehash:
x.my_method_name # => somehash
Find the object the method is being invoked on. If it's easily replaced and doesn't have that much more functions, you can pass this double instead on it's place. If that is not the case, you can stub the method on that object by doing:
said_object.stub(my_method_name: somehash)
If you want to stub it for all instances of a class, you could do:
TheObjectsClass.any_instance.stub(my_method_name: somehash)
Disclaimer: The topic is a bit more complex and subject to debate. Don't consider this as a good testing practice, it just aims to help you understand how to use rspec.
You said this is related to networking. You can consider using VCR to simulate actual requests.
Since the class you are testing is the one on which this method is called, you should be stubbing the method on the same class
allow(<your_class_instance>).to receive(:my_method_name).and_return(<>)
I am assuming this method is an instance method. If its a class method, you will have to stub it at the class level

What is the difference in calling a method explicitely and implicitely?

As per my understanding, in ruby we cannot call private method on self (calling private methods on self explicitly is not possible). If you call a method without any receiver, then it gets called on self, Then why cant we call a private method with self itself?
Sorry but I didn't really get what exactly is the difference in calling explicitly and implicitly(with self and without self).
I know that I may get down votes but still want to know. Can anyone tell me please.
At least in MRI, these concepts are identical. An explicit call is a public call, an implicit call is a private call.
The parser recognizes three kinds of method calls:
methods with an explicit receiver e.g. obj.foo(1)
methods with an implicit receiver e.g. foo(1)
methods with an implicit receiver and no arguments e.g. foo
The evaluator recognizes each of these as a different "call type". These types are (respectively):
CALL_PUBLIC
CALL_FCALL
CALL_VCALL
This call type is checked before making the call:
if (((noex & NOEX_MASK) & NOEX_PRIVATE) && scope == CALL_PUBLIC) {
return NOEX_PRIVATE;
}
I.e. if the method is private and the call type is public, don't call the method (protected calls work the same way but also check the receiver's class).
So whenever there is an explicit receiver (even if it's self inside an instance method definition), that call is a "public call".

Does ruby call initialize method automatically?

Do I need to explicitly initialize an object if an initialize method is included in class definition?
No, Ruby does not call initialize automatically.
The default implementation of Class#new looks a bit like this:
class Class
def new(*args, &block)
obj = allocate
obj.initialize(*args, &block)
obj
end
end
[Actually, initialize is private by default so you need to use obj.send(:initialize, *args, &block).]
So, the default implementation of Class#new does call initialize, but it would be perfectly possible (albeit extremely stupid) to override or overwrite it with an implementation that does not.
So, it's not Ruby that calls initialize, it's Class#new. You may think that's splitting hairs, because Class#new is an integral part of Ruby, but the important thing here is: it's not some kind of language magic. It's a method like any other, and like any other method it can be overridden or overwritten to do something completely different.
And, of course, if you don't use new to create an object but instead do it manually with allocate, then initialize wouldn't be called either.
There are some cases where objects are created without calling initialize. E.g. when duping or cloneing, initialize_dup and initialize_clone are called instead of initialize (both of which, in turn, call initialize_copy). And when deserializing an object via, say, Marshal, its internal state is reconstructed directly (i.e. the instance variables are set reflectively) instead of through initialize.
Yes, it's called from new method, which you use to create objects.
It depends on your definition of "explicit". Usually you need to, even if there are no arguments:
object = MyClass.new(...)
In some cases there are factory methods that produce instances you can use, creating a form of implicit initialization:
object = MyClass.factory_method(...)
This would have the effect of calling MyObject.new internally.
There are some libraries which have rather unusual method signatures, like:
object = MyClass(...)
object = MyClass[...]
The effect is the same, as these might look odd but are just method calls.

Do ruby Proc/lambda have a 'this' function like javascript closure ?

In javascript closure, 'this' reference to the object which actually make the function call.
Do ruby Proc/lambda have 'this' function too?
If not, what should I do to if I want 'this' in ruby? except passing the current object to Proc/lambda by parameters.
this is not part of the concept of a function or closure in general. A function is simply a thing you can call with arguments; what does "current object" has to do with it? this existing in all functions in JavaScript comes from the peculiar way that methods work in that language.
In JavaScript, all functions have a concept of this because in JavaScript, there is no separation between methods and functions. Any function could potentially be used as a method; you can add a method to an object simply by assigning a function as an attribute of the object. Furthermore, in JavaScript, a function does not have an explicit parameter for the current object (unlike e.g. Python); so how does a method have access to its object? When you run a method call expression, it will pass the object that you called it on as an implicit this parameter to the function. However, if you get the function out using the attribute and call it manually just like any other function, this will be the global object (or in strict mode, undefined).
In other words, in JavaScript when you get a method out of an object by attribute, it is an "unbound method" -- it does not know the object it came from; and conversely when you put a function into an object as a method by attribute, that function did not need to know the object to start with -- the object will be passed to it magically by the method call syntax at the time it is called. You can also artificially supply the this argument to a function by using the .call() or .apply() methods on the function (obj.foo(x) is equivalent to obj.foo.call(obj, x)).
In Ruby, there is complete separation between methods and anonymous functions. Anonymous functions, created using lambda, proc, or Proc.new, etc. are data, and can be stored in variables. They are called with different syntax (call or []) than methods. Methods are defined using def, and you can't get it as data by simply writing its name (that will call it). It is possible to get a method out of an object using the method method on an object, giving the method name, and it returns a Method object. You can use a Method object like a Proc object, e.g. you can call call on it; you can even convert it to a Proc with to_proc. Unlike JavaScript, there is a distinction between bound methods (class Method) an unbound methods (class UnboundMethod). When you get a method out of an object, it is bound -- it knows its object; you can unbind it and bind it to another object if you want.
Also, in Ruby, you can't just take a Proc and just attach it to an object and make it a method, because methods have syntax (e.g. #some_var) that are not valid in Proc. To add a method to an object, you would use instance_exec and put the method definition (def) in the block.
So in short, the concept of this in closures deals with a unique situation in JavaScript not found in most languages. And in particular, the issue does not come up in Ruby because Ruby's objects' methods are bound methods, and also one cannot arbitrarily insert closures as methods.
P.S. others have commented on capturing the self from where a closure is defined into the closure. However, that's not what this in JavaScript is about at all.
You can use self if you initialize the lambda or proc within a Ruby object. For example:
class Example
def name
"Example"
end
def test
lambda{ puts self.name}.call
end
end
example = Example.new
example.test # "Example"
For a more detailed explanation of Ruby's self see: http://sidtalk.wordpress.com/2008/10/06/what-exactly-is-ruby-self/.

Resources