OOP in Corona, accessing vars from outside class - oop

looking for some help with accessing variables from outside a Corona OOP class. Here's the bare-bones code:
module(..., package.seeall)
local widget = require "widget"
picker = {}
picker.__index = picker
function picker.new()
local picker_object = {}
setmetatable(picker_object,picker)
picker_object.theHour = 12
picker_object.theMin = 0
picker_object.am = true
return picker_object
end
function picker:getHour()
return self.theHour
end
function picker:getMin()
return self.theMin
end
self is coming back as nil when I try and call getHour and getMin from outside the class. What syntax should I use instead to return my theHour and theMin variables?
Thanks!!

I tried out your code and there's nothing wrong with it. The problem is probably in the way you're accessing this module. Here's my main.lua that works with your code (I gonna guess your file is named picker.lua):
local picker = require "picker"
local picker_obj = picker.picker.new()
-- the first picker is the module (picker.lua)
-- the second is the picker class in the file
print("minute: " .. picker_obj:getMin())
print("hour: " .. picker_obj:getHour())
Also, The module(..., package.seeall) command has been deprecated, see this blog post for a better way to make your module. If you use this method to create your module and still call your file picker.lua, the first two lines in my main.lua would change to:
local picker = require "picker"
local picker_obj = picker.new()
Here's the simplest way I would modify your code to use the new way of creating modules. Only the beginning and end change, everything else stays the same:
-- got rid of module(), made picker local
local picker = {}
picker.__index = picker
... -- all the functions stay the same
return picker

Related

Variables lose value swift

I have an app that stores a players name and score inside the variables
"CurrentPlayer" and "CurrentPlayerScore". this works just fine. but when I switch to another view, which displays the name and their score (which works fine.), and then I switch back both my variables lose their value. any help is appreciated and i'm pretty new to swift so the clearer the better. thanks. (also I have used the prepare for segue method, which works for passing information to my next view controller but not back)
You can use a global variables. There are defined in the global scope and can be accessed from everywhere in your project.
import UIKit
// globale Variablen
var global_address : String = ""
var global_username : String = ""
var global_password : String = ""
// globale Variablen
class ViewController
{
// ....
}

How to set Attribute to PDO connection in Codeigniter

How to set attributes (PDO::ATTR_ERRMODE) on the PDO database handle in Codeigniter?
I think a better option is to use a MY_Model (which you then extend and this is available then across the application) and define something like this in the construct:
$this->db->conn_id->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
Note conn_id allows you to access the main PDO object.
There are two ways:
1. The lazy (hacky) way
Add to the following code into system/core/database/drivers/pdo/pdo_driver.php (in CI 3):
public function db_connect($persistent = FALSE)
{
$this->options[PDO::ATTR_PERSISTENT] = $persistent;
// Added code start
$this->options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
// Added code end
try
{
return new PDO($this->dsn, $this->username, $this->password, $this->options);
...
}
2. The right way
Extend Database Driver and add the same line
Note: If you will set PDO::ERRMODE_EXCEPTION in Codeigniter it will show exception errors even in Production environment.

Rspec: Stubbing out a where statement in a controller test

I'm writing the following test:
let!(:city_areas) { FactoryGirl.create_list(:city_area, 30) }
before {
#city_areas = mock_model(CityArea)
CityArea.should_receive(:where).and_return(city_areas)
}
it 'should assign the proper value to city areas variable' do
get :get_edit_and_update_vars
assigns(:city_areas).should eq(city_areas.order("name ASC"))
end
to test the following method:
def get_edit_and_update_vars
#city_areas = CityArea.where("city_id = '#{#bar.city_id}'").order("name ASC").all
end
However, it fails out, saying that there's no method 'city_id' for nil:NilClass, leading me to believe it's still attempting to use the instance variable #bar.
How do I properly stub out this where statement to prevent this?
Why are you doing #city_areas = mock_model(CityArea) and then you never use #city_areas again?
I would test it this way:
inside the model CityArea create a named scope for this: where("city_id = '#{#bar.city_id}'").order("name ASC")
then in your controller spec you do
describe 'GET get_edit_and_update_vars' do
before(:each) do
#areas = mock('areas')
end
it 'gets the areas' do
CityArea.should_receive(:your_scope).once.and_return(#areas)
get :get_edit_and_update_vars
end
it 'assign the proper value to city areas variable' do
CityArea.stub!(:your_scope => #areas)
get :get_edit_and_update_vars
assigns(:city_areas).should eq(ordered)
end
end
and you should also create a spec for that new scope on the model spec
just a tip, you shouldn't use should_receive(...) inside the before block, use stub! inside before and use should_receive when you want to test that method is called
also, you shouldn't need to use factorygirl when testing controllers, you should always mock the models, the model can be tested on the model spec

Lua global variable in module staying nil?

Im starting to learn Lua modules a bit, and I am having troubles with a small part in my Lua.
Everytime I change my variable it reverts back to nil.
myModule.lua
--I should note that client is a number.
module(..., package.seeall)
local LoggedIn = { }
function isLogged( client )
return LoggedIn[client]
end
function logIn(client)
table.insert(LoggedIn,client,true)
end
function logOut(client)
table.remove(LoggedIn,client)
end
main.lua an event happens
package.loaded.myModule= nil; require "myModule"
function event( client )
myModule.logIn(client)
end
function event_2( client )
myModule.logOut(client)
end
EDIT: Using functions instead, and making it local variable.
It is still returning nil even though I can confirm the logIn function happened with no errors. Without even using the logout function yet.
Any thoughts?
but later on in main.lua I check if client is logged in and it just returns nil.
Is this just a limitation of modules or am I just accessing the variable wrong.
I should note I need to be able to do this in other Luas that acces myModule.lua too.
Thanks in advance
You don't really give us enough code to fully help you, but this is a working example I set up based on what little example you gave us:
-- myModule.lua
module(..., package.seeall)
LoggedIn = {}
function isLoggedIn(client)
return LoggedIn[client] ~= nil
end
function LogIn(client)
LoggedIn[client] = true
end
function LogOut(client)
LoggedIn[client] = nil
end
and to test it:
-- main.lua
require "myModule"
myModule.LogIn("Joe")
myModule.LogIn("Frank")
print(myModule.isLoggedIn("Bill"))
print(myModule.isLoggedIn("Frank"))
myModule.LogOut("Joe")
print(myModule.isLoggedIn("Joe"))
this prints out as expected:
false
true
false
so my guess is that you are not checking the conditions correctly for LoggedIn[client] being empty, or you never actually remove entries from the LoggedIn table when someone 'logs out'.
The following using your own code (assuming you fix typo in funtion) works (it prints true\nnil):
package.loaded.myModule= nil; require "myModule"
function event( client )
myModule.LoggedIn[client] = true
end
event("foo")
print(myModule.isLogged("foo"))
A better way to do this would be to add a function logIn as #Mike suggested and avoid using module(); you can use something like this instead:
local myModule = require "myModule"
function event( client )
myModule.logIn(client)
end
event("foo")
print(myModule.isLogged("foo"))
print(myModule.isLogged("bar"))
And myModule.lua becomes:
local LoggedIn = { }
function isLogged( client )
return LoggedIn[client]
end
function logIn( client )
LoggedIn[client] = true
end
return { LoggedIn = LoggedIn, isLogged = isLogged, logIn = logIn }

Testing Coffeescript with Jasmine and Rails 3.1

Say I have a class in Coffeescript:
class MyGame
constructor: () ->
#me = new Player
#opponents = [new Player, new Player]
which would like to test in Jasmine:
describe "MyGame", ->
beforeEach ->
window.game = new MyGame
it "should have two players", ->
expect(window.game.opponents.length).toEqual 2
But I get the error TypeError: Result of expression 'window.game.opponents' [undefined] is not an object.?
The window.game approach also seem awkward to me. If I try to define it as #game = new MyGame I get the error ReferenceError: Can't find variable: MyGame but I guess that has something to do with the way Coffeescript is wrapping things up?
UPDATE: The problem seems more like a reference problem as described above. I'm running with guard-jasmine which looks like
guard 'jasmine', :all_on_start => false, :all_after_pass => false do
watch(%r{app/assets/javascripts/(.+)\.(js\.coffee|js)}) { |m| "spec/javascripts/#{m[1]}_spec.#{m[2]}" }
watch(%r{spec/javascripts/(.+)_spec\.(js\.coffee|js)}) { |m| "spec/javascripts/#{m[1]}_spec.#{m[2]}" }
watch(%r{spec/javascripts/spec\.(js\.coffee|js)}) { "spec/javascripts" }
end
and my jasmine.yml file has:
src_files:
- "app/assets/**/*.js"
- "app/assets/**/*.coffee"
spec_files:
- '**/*[sS]pec.js.coffee'
asset_pipeline_paths:
- app/assets
- spec/javascripts
I get the an ReferenceError: Can't find variable: MyGame so I figure it's either something with the Rails 3.1 asset pipeline or the way Coffeescript wraps objects.
try defining your coffeescript class using the # operator as such:
class #MyGame
constructor: () ->
#me = new Player
#opponents = [new Player, new Player]
this will allow you to access the class from anywhere, such as from your jasmine tests, and also you can get away from attaching testing variables to window:
describe "MyGame", ->
beforeEach ->
#game = new MyGame
it "should have two players", ->
expect(#game.opponents.length).toEqual 2
the reason for this is that coffeescript goes out of its way to avoid introducing global variables by wrapping everything in a closure. unfortunately, this can be undesirable for object-oriented code. using the # operator attaches the class definition to the global this, which is window, and thus allows you to instantiate your classes as you like. you may have some global vars in your global space now, your classes, but for me its an ok trade-off. hope this helps!
I wasn't willing to accept modifying the namespace of my code by using an # symbol in front of all my backbone classes, so I dug around some more and the solution that worked for me was to require the application file in my spec/javascripts/spec.js.coffee file
#= require application
window.game = () -> new MyGame
This will assign a function that returns a new MyGame to window.game. Did you not just want the new instance directly?
window.game = new MyGame
The window.game approach also seem awkward to me.
How about this
describe "MyGame", ->
game = null
beforeEach ->
game = new MyGame
it "should have two players", ->
expect(game.opponents.length).toEqual 2
I have solved the problem by defining every class as class window.MyGame for example. In the spec files I put #= require my_file_name in the top.
Furthermore I have placed both jasminerice.js.coffee and jquery.js in app/assets/javascripts. This might not be the best solution as I assume they should be placed in spec/javascripts/helpers as my spec.js.coffee's content is #=require_tree ./.
I'm aware that this is not very elegant but it might help others in the same situation. #Thilo thanks for your inputs.