Search code examples
rubycucumberjrubyfactory-bot

pass a module and class name as an argument to a ruby function


Alright, I have the following method:

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   

I want the target_database and target_table parameters to be module and class names, respectively; Which will then be used in the function in place of RptMcksWorkdb::CtmStagingExtractControl.

So my final function would look similar to this:

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   

EDIT: Here is my working code:

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

Solution

  • If you're on rails,

    You could use a combination of camelecase/classify and constantize

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

    that'll give something like

    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