Setting units in Component Definition DC

SketchUp uses inches internally, and DCs usually do also.

However, you can set the formula units for your of attributes to be in any units. But this may (or may not,) make them harder to use.

Where DC_DICT is "dynamic_attributes"

To get the user’s model units (as a DC unit string name):

EDIT: This example has been edited to use constants to avoid errors using the wrong integer id literals.

def get_model_units()
  opts = Sketchup.active_model.options["UnitsOptions"]
  unit_format = opts["LengthFormat"]
  if unit_format != Length::Decimal
    if unit_format == Length::Fractional ||
    unit_format == Length::Architectural
      "INCHES" # Architectural or Fractional
    elsif unit_format == Length::Engineering
      "FEET"   # Engineering
    else
      "DEFAULT"
    end
  else # Decimal ( unit_format == 0 )
    case opts["LengthUnit"]
    when Length::Inches
      "INCHES"
    when Length::Feet
      "FEET"
    when Length::Centimeter
      "CENTIMETERS"
    when Length::Millimeter
      "MILLIMETERS"
    when Length::Meter
      "METERS"
    else
      "DEFAULT"
    end
  end
end

[details=(For the record: the previous code using erroneous integer literals…)]

def get_model_units()
  opts = Sketchup.active_model.options["UnitsOptions"]
  unit_format = opts["LengthFormat"]
  if unit_format != 0
    if unit_format == 1 || unit_format == 3
      "INCHES" # Architectural or Fractional
    elsif unit_format == 2
      "FEET"   # Engineering
    else
      "DEFAULT"
    end
  else # Decimal ( unit_format == 0 )
    case opts["LengthUnit"]
    when 0
      "INCHES"
    when 1
      "FEET"
    when 2 # ERROR! --> should be 3
      "CENTIMETERS"
    when 3 # ERROR! --> should be 2
      "MILLIMETERS"
    when 4
      "METERS"
    else
      "DEFAULT"
    end
  end
end
```[/details]

To set a DC's length units:

_NOTE: This is the attribute that toggles between `"INCHES"` and `"CENTIMETERS"` when you click the ruler icon in the **Component Options** dialog._
```ruby
def set_dc_length_units(
  dc, # the dynamic component's definition
  units = get_model_units() # "DEFAULT" is to use model units
)
  dc.set_attribute( DC_DICT, "_lengthunits", units )
end

To set an individual attribute’s formula units:

def set_dc_attribute_units(
  dc, # the dynamic component's definition
  attr_name, # the name of the dc attribute
  units = get_model_units() # "DEFAULT" is to use model units
)
  dc.set_attribute( DC_DICT, "_#{attr_name}_formulaunits", units )
end