如何从同一模块内的 class 调用方法
How to call a method from a class inside the same module
如何从结构或 class 调用 redis?
module A::Cool::Module
redis = Redis.new(host: ENV["REDIS_DEV_HOST"], port: 18163)
redis.auth(ENV["REDIS_DEV_AUTH"])
struct CoolStruct
def CoolFunciton
redis # => undefined method 'redis' for A::Cool::Module:Module
end
end
end
我尝试了以下但没有成功
module A::Cool::Module
@@redis = Redis.new(host: ENV["REDIS_DEV_HOST"], port: 18163)
@@redis.auth(ENV["REDIS_DEV_AUTH"])
struct CoolStruct
def CoolFunciton
@@redis # => can't infer the type of class variable '@@redis'
end
end
end
module A::Cool::Module
module DB
redis = Redis.new(host: ENV["REDIS_DEV_HOST"], port: 18163)
redis.auth(ENV["REDIS_DEV_AUTH"])
end
struct CoolStruct
include A::Cool::Module::DB
def CoolFunciton
redis # => undefined local variable or method 'redis'
end
end
end
module A::Cool::Module
module DB
redis = Redis.new(host: ENV["REDIS_DEV_HOST"], port: 18163)
redis.auth(ENV["REDIS_DEV_AUTH"])
end
struct CoolStruct
include A::Cool::Module::DB
def CoolFunciton
A::Cool::Module::DB.redis # => undefined method 'redis'
end
end
end
我真的不知道该怎么做。
而且我不想为每个需要 redis 的 class 创建一个 redis 连接。
案例在 Crystal 中很重要。一个模块可以有常量,这些常量在整个模块范围内都可以访问(注意大写):
module A::Cool::Module
REDIS = ...
...
end
(此外,您应该真正使用 snake_case
,而不是 TitleCase
作为方法名称;因此 cool_function
,而不是 CoolFunction
。)
如何从结构或 class 调用 redis?
module A::Cool::Module
redis = Redis.new(host: ENV["REDIS_DEV_HOST"], port: 18163)
redis.auth(ENV["REDIS_DEV_AUTH"])
struct CoolStruct
def CoolFunciton
redis # => undefined method 'redis' for A::Cool::Module:Module
end
end
end
我尝试了以下但没有成功
module A::Cool::Module
@@redis = Redis.new(host: ENV["REDIS_DEV_HOST"], port: 18163)
@@redis.auth(ENV["REDIS_DEV_AUTH"])
struct CoolStruct
def CoolFunciton
@@redis # => can't infer the type of class variable '@@redis'
end
end
end
module A::Cool::Module
module DB
redis = Redis.new(host: ENV["REDIS_DEV_HOST"], port: 18163)
redis.auth(ENV["REDIS_DEV_AUTH"])
end
struct CoolStruct
include A::Cool::Module::DB
def CoolFunciton
redis # => undefined local variable or method 'redis'
end
end
end
module A::Cool::Module
module DB
redis = Redis.new(host: ENV["REDIS_DEV_HOST"], port: 18163)
redis.auth(ENV["REDIS_DEV_AUTH"])
end
struct CoolStruct
include A::Cool::Module::DB
def CoolFunciton
A::Cool::Module::DB.redis # => undefined method 'redis'
end
end
end
我真的不知道该怎么做。 而且我不想为每个需要 redis 的 class 创建一个 redis 连接。
案例在 Crystal 中很重要。一个模块可以有常量,这些常量在整个模块范围内都可以访问(注意大写):
module A::Cool::Module
REDIS = ...
...
end
(此外,您应该真正使用 snake_case
,而不是 TitleCase
作为方法名称;因此 cool_function
,而不是 CoolFunction
。)