将模块和类名作为参数传递给ruby函数

时间:2014-12-23 15:13:56

标签: ruby cucumber jruby factory-bot

好的,我有以下方法:

def update_window_for_ctm_staging_extract(target_database,target_table,table_name)                  
    RptMcksWorkdb::CtmStagingExtractControl.                                                        
        where(:src_tablename => table_name).                                                                                 
        update(:from_date_dttm => from_date_dttm, :to_date_dttm => to_date_dttm, :sequence_no => 1) 
end   

我希望target_database和target_table参数分别是模块和类名;然后将在函数中使用哪个代替RptMcksWorkdb::CtmStagingExtractControl

所以我的最终功能看起来与此相似:

def update_window_for_ctm_staging_extract(target_database,target_table,table_name)                  
        target_database::target_table.                                                        
            where(:src_tablename => table_name).                                                                                 
            update(:from_date_dttm => from_date_dttm, :to_date_dttm => to_date_dttm, :sequence_no => 1) 
    end   

编辑:这是我的工作代码:

def update_control_table_window(target_database, target_table, table_name)
     model = "#{target_database.camelcase}::#{target_table.camelcase}".constantize
     model.
         where(:src_tablename => table_name).
         update(:from_date_dttm => from_date_dttm, :to_date_dttm => to_date_dttm, :sequence_no => 1)
 end

2 个答案:

答案 0 :(得分:0)

如果你在轨道上,

您可以结合使用camelecase / classifyconstantize

> model = "#{'my_database'.camelcase}::#{'here_is_some_table'.camelcase}".constantize
=> MyDatabase::HereIsSomeTable  # Only work if you actually have such a constant

这会给出像

这样的东西
def update_window_for_ctm_staging_extract(target_database, target_table, table_name)
    model = "#{'target_database'.camelcase}::#{'target_table'.camelcase}".constantize
    model.
        where(src_tablename: table_name).
        update(from_date_dttm: from_date_dttm, to_date_dttm: to_date_dttm, sequence_no: 1)
end

答案 1 :(得分:0)

最简单的方法是将所需的类传递给方法,而不是分别传递包含模块和类:

def update_window_for_ctm_staging_extract(target_class, table_name)
  target_class.
    where(src_tablename: table_name).
    update(from_date_dttm: from_date_dttm, to_date_dttm: to_date_dttm, sequence_no: 1)
end

update_window_for_ctm_staging_extract(
  RptMcksWorkdb::CtmStagingExtractControl, :customers)

否则,您需要反射性地获取常量的值:

def update_window_for_ctm_staging_extract(target_database, target_table, table_name)
  const_get(target_database).const_get(target_table).
    where(src_tablename: table_name).
    update(from_date_dttm: from_date_dttm, to_date_dttm: to_date_dttm, sequence_no: 1)
end

update_window_for_ctm_staging_extract(
  :RptMcksWorkdb, :CtmStagingExtractControl, :customers)