aphexlog
aphexlog

Reputation: 1775

Ruby/chef: IF ELSE statement

Trying to set template variable {USE_EXISTING_SCHEMA} to = true or false based on whether or not {CREATE_OID_SCHEMA} is = to true. should I be using == or = when specifying the IF condition of {CREATE_OID_SCHEMA}?

case node['fmw']['shortname']
      when /oid1/
        IS_SECOND_OID_INSTALL = "false"
        CONFIGURE_OVD_COMPONENT = "true"
        CREATE_OID_SCHEMA = "true"
          if CREATE_OID_SCHEMA = "true" then
            USE_EXISTING_SCHEMA = "false"
          else USE_EXISTING_SCHEMA = "true"
      when /oid2/
        IS_SECOND_OID_INSTALL = "true"
        CONFIGURE_OVD_COMPONENT = "false"
        CREATE_OID_SCHEMA = "false"
          if CREATE_OID_SCHEMA = "true" then
            USE_EXISTING_SCHEMA = "false"
          else USE_EXISTING_SCHEMA = "true"
    end

Upvotes: 0

Views: 13847

Answers (1)

Holger Just
Holger Just

Reputation: 55758

The = operator is always an assignment operator, even in an if statement. Thus, your statement

if CREATE_OID_SCHEMA = "true" then

always assigns the string "true" to the CREATE_OID_SCHEMA constant (and outputs a warning at that). Since the string "true" is also truethy, the if statement will always match.

Going forward, you probably want to update your code as follows:

case node['fmw']['shortname']
when /oid1/
  is_second_oid_install = "false"
  configure_ovd_component = "true"
  create_oid_schema = "true"

  if create_oid_schema == "true"
    use_existing_schema = "false"
  else
    use_existing_schema = "true"
  end
when /oid2/
  is_second_oid_install = "true"
  configure_ovd_component = "false"
  create_oid_schema = "false"

  if create_oid_schema == "true"
    use_existing_schema = "false"
  else
    use_existing_schema = "true"
  end
end

In the code above, I have performed the following changes:

  • In the if statement, I use the comparison operator == instead of the assignment operator =.
  • variables in Ruby should always start with a lower-case letter and use snake_case. Bare words starting with an upper-case letter are considered constants in Ruby which should only be assigned once.
  • The then keyword should usually not be used. Use newlines instead.

When further updating your code, you should use real boolean values (true and false) instead of strings containing the word. That way, you can shorten your comparisons and better reflect your intentions. Generally, all values but false and nil are truethy in Ruby (and thus match in an if statement). This includes all strings, numbers, regular expressions, ...

Upvotes: 1

Related Questions